class Bug {
private:
int nLegs;
int nColor;
public:
int nType;
Bug (int legs, int color);
void PrintBug() {}
};
class FlyBug:public Bug {
int nWings;
public:
FlyBug(int legs, int color, int wings);
};
Bug::Bug(int legs, int color):nLegs(legs), nColor(color) {
}
// 错误的构造函数
FlyBug::FlyBug(int legs, int color, int wings) {
nLeg = legs; // 不能访问
nColor = color; // 不能访问
nWings = wings;
}
// 正确的
FlyBug::FlyBug(int legs, int color, int wings):Bug(legs, color) {
nWings = wings;
}
- 在创建派生类的对象时,需要先调用基类的构造函数
- 调用基类构造函数的两种方式
- 显式方式:直接调用
- derived::derived(arg_derived-list):base(arg_base-list)
- 隐式方式:在派生类的构造函数中,省略基类构造函数时,派生类自动调用基类的默认构造函数
- 如果没有无参构造函数,编译会出错
- 显式方式:直接调用
- 派生类的析构函数被执行时,执行完派生类的析构函数后,自动调用基类的析构函数
封闭派生类对象的构造函数执行顺序
在创建派生类的对象时:
- 先执行基类
- 在执行成员对象类
- 最后执行自己
消亡的时候:
- 先执行自己的
- 再执行成员对象的
- 最后执行基类的