1. class Bug {
  2. private:
  3. int nLegs;
  4. int nColor;
  5. public:
  6. int nType;
  7. Bug (int legs, int color);
  8. void PrintBug() {}
  9. };
  10. class FlyBug:public Bug {
  11. int nWings;
  12. public:
  13. FlyBug(int legs, int color, int wings);
  14. };
  15. Bug::Bug(int legs, int color):nLegs(legs), nColor(color) {
  16. }
  17. // 错误的构造函数
  18. FlyBug::FlyBug(int legs, int color, int wings) {
  19. nLeg = legs; // 不能访问
  20. nColor = color; // 不能访问
  21. nWings = wings;
  22. }
  23. // 正确的
  24. FlyBug::FlyBug(int legs, int color, int wings):Bug(legs, color) {
  25. nWings = wings;
  26. }
  • 在创建派生类的对象时,需要先调用基类的构造函数
  • 调用基类构造函数的两种方式
    • 显式方式:直接调用
      • derived::derived(arg_derived-list):base(arg_base-list)
    • 隐式方式:在派生类的构造函数中,省略基类构造函数时,派生类自动调用基类的默认构造函数
      • 如果没有无参构造函数,编译会出错
  • 派生类的析构函数被执行时,执行完派生类的析构函数后,自动调用基类的析构函数

    封闭派生类对象的构造函数执行顺序

    在创建派生类的对象时:
  1. 先执行基类
  2. 在执行成员对象类
  3. 最后执行自己

消亡的时候:

  1. 先执行自己的
  2. 再执行成员对象的
  3. 最后执行基类的