基本语法
语法: class 子类名:继承方式 父类名
继承方式:
- 公共继承
- 保护继承
- 私有继承
class teacherX
{
// 父类
public:
int teax_pub;
void teaxfun()
{
cout << "teacherx class" << endl;
}
void teaxfun(int a)
{
cout << "teacherx 100 class" << endl;
}
protected:
int teax_pro;
private:
int teax_pri;
};
class teacherXX
{
public:
teacherXX()
{
teaxx_pub = 10;
}
int teaxx_pub;
};
class student :public teacherX// 子类
{
// 公共继承
// 语法:class 子类名:继承权限 父类名
public:
void teaxfun()
{
cout << " student class" << endl;
}
int std_pub;
};
公共继承
将父类中的成员按照权限不变的方式继承子类中。
保护继承
将父类中的成员继承到子类中,并且权限修改为保护权限。
私有继承
将父类中的成员继承到子类中,并且权限修改为私有权限。
子类和父类构造和析构顺序
构造:先有父类构造,再有子类构造
析构:先析构子类,在析构父类
注:析构的顺序一般与构造的顺序相反。
子类和父类成员同名处理方式
同名成员变量:
- 调用子类中的teaAndstd变量,直接通过子类的对象调用即可。
- 调用父类中中的teaAndstd变量,需要增加作用域
代码:
student stdL;
stdL.teaAndstd; // 调用子类的teaAndstd变量
stdL.teacher::teaAndstd; // 调用父类的teaAndstd变量
同名成员函数:
student lc;
lc.teafun();
lc.teacher::teafun();
lc.teacher::teafun(100);
结果:
student class
teacher class
teacher 100 class
继承多个父类
语法:class 子类名:继承方式 父类1名, 继承方式 父类2名 …
class student :public teacherX, public teacherXX
虚继承
在继承方式前面加上关键字: virtual
实列:
class Base
{
public: int age = 10;
};
class boy1:virtual public Base {};
class boy2 :virtual public Base {};
class underBoy:public boy1, public boy2 {};
underBoy grandson;
grandson.boy1::age = 10;
grandson.boy2::age = 100;
cout << grandson.boy1::age << endl;
cout << grandson.boy2::age << endl;
cout << grandson.age << endl;
结果:
100
100
100
请按任意键继续. . .
虚继承的作用是为了解决变量二义性的问题。虽然上述示例通过不同的类继承了age,实则age只有一份。而类boy1和boy2是通过指针的方式去访问base类下的age。因此当以不同的方式修改age时,所有类下的age都会发生变化。
Note:
- 不管是那种继承方式都只能继承父类中的公共和保护成员。
- 继承之后父类中所有的非静态成员属性都会被子类继承。在程序中不能访问父类的私有成员,是因为被编译器隐藏了。如下,子类的字节大小为16,说明继承了子类中的所有成员。
sizeof(student) = 16