本文主要是介绍C++nbsp;继承,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
注:参考东南大学《C++程序设计教程》视频,主讲老师:何洁月。此内容为自学时所记笔记
第七章 类的继承与派生
继承:保持已有类的特性而构成新类的过程 目的:实现代码重用
派生:在已有类的基础上新增自己的特性而产生新类的过程 目的:原程序进行改造吗
(1)吸收基类 。(2)改造 同名覆盖。(3)新增加。
基类--->派生类
公有继承:class B{};
class A:public B{};
派生类的“成员函数”可以访问基类public ,protected。
派生类的“对象”只能访问基类的public。
例:
#include
using namespace std;
class Point
{
public :
// Point (float x,float y){X=x;Y=y;}
void InitP(float x,float y){X=x;Y=y;}
float getX(){return X;}
float getY(){ return Y;}
void Print();
void Move(float x,float y);
private :
float X,Y;
};
void Point::Move(float x,float y){
X+=x;
Y+=Y;
}
void Point::Print(){
cout<<getX()<<" "<<getY()<<endl;
}
class Rectangle:public Point
{
public :
void InitR(float x,float y,float w,float h){
InitP(x,y);
W=w;
H=h;
}
float getW(){return W;}
float getH(){return H;}
//void Print();
private:
float W,H;
};
int main()
{
Rectangle r;
r.InitR(1,1,1,1);
r.Move(1,1);
r.Print();
return 0;
}
私有继承:
class B{};
class A:private B{};
public 和protected 成员以private 出现在派生类中,
派生类的成员函数不能访问基类的private成员。
派生类的对象不能访问任何成员,想要访问,必须重新构造方法
class Rectangle:private Point
{
public :
void InitR(float x,float y,float w,float h){
InitP(x,y);
W=w;
H=h;
}
void Move(float x,float y); //重新构造
void Print(); //重新构造
float getX(){return Point::getX();}
float getW(){return W;}
float getH(){return H;}
//void Point::Print();
private:
float W,H;
};
void Rectangle::Move(float x,float y){
Point::Move(x,y);
}
void Rectangle::Print(){
Point::Print();
cout<<W<<"--"<<H<<endl;
}
保护继承(protected)
class B{};
class A :protected B{};
派生类的成员可以访问基类的public,protected
派生类的对象不能访问基类的所有成员。
特点与作用:派生类外不能访问基类的protected成员 ,
派生类类内可以访问基类的......。
例:
class A
{
public :
void setA(int aa){a=aa;}
int getA(){return a;}
protected :
int a;
};
class B:protected A
{
public :
int getB(){return b;}
void changeA(){a=a*2;} //派生类内可以对基类protected成员操作
int getA(){A::getA();}
void setA(int x){A::setA(x);}
private:
int b;
};
#include
using namespace std;
int main()
{
B b;
b.setA(10);
b.changeA();
cout<<b.getA()<<endl;
}
总结:三种继承,派生类的成员访问是一样的,派生类的对象访问
不一样,
派生类中的成员属性,public->protected->private 变换
public protected private
:public public
第七章
继承:保持已有类的特性而构成新类的过程
派生:在已有类的基础上新增自己的特性而产生新类的过程
基类--->派生类
公有继承:class B{};
例:
#include
using namespace std;
class Point
{
public :
private :
};
void Point::Move(float x,float y){
}
void Point::Print(){
}
class Rectangle:public Point
{
public :
private:
};
int main()
{
}
私有继承:
{
public :
private:
};
void Rectangle::Move(float x,float y){
}
void Rectangle::Print(){
}
保护继承(protected)
例:
class A
{
public :
protected :
};
class B:protected A
{
public :
private:
};
#include
using namespace std;
int main()
{
}
总结:三种继承,派生类的成员访问是一样的,派生类的对象访问
:public