派生类的构造函数

1.PNG

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

2.PNG

派生类的析构函数

3.PNG

派生类析构函数的调用顺序

4.PNG

代码实例

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class bug
  4. {
  5. private:
  6. int nLegs;
  7. int color;
  8. public:
  9. int type;
  10. bug(int l, int c, int t);
  11. void print_bug(void);
  12. };
  13. bug::bug(int l, int c, int t) : nLegs(l), color(c), type(t){};
  14. void bug::print_bug(void)
  15. {
  16. cout << "Legs: " << nLegs << endl;
  17. cout << "Color: " << color << endl;
  18. cout << "Type: " << type << endl;
  19. }
  20. //-----------------------------------------------------------------------------------------------
  21. class flybug : public bug
  22. {
  23. private:
  24. int nWings;
  25. public:
  26. flybug(int l, int c, int t, int w);
  27. void print_flybug(void);
  28. };
  29. flybug::flybug(int l, int c, int t, int w) : bug(l, c, t), nWings(w){};
  30. void flybug::print_flybug(void)
  31. {
  32. print_bug();
  33. cout << "Wings: " << nWings << endl;
  34. }
  35. //----------------------------------------------------------------------------------------------
  36. int main(void)
  37. {
  38. flybug fly(8, 1, 2, 4);
  39. fly.type = 3;
  40. fly.print_bug();
  41. fly.print_flybug();
  42. return 0;
  43. }
  44. /*
  45. Legs: 8
  46. Color: 1
  47. Type: 3
  48. Legs: 8
  49. Color: 1
  50. Type: 3
  51. Wings: 4
  52. */
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class c
  4. {
  5. public:
  6. c(void) { cout << "C Constructed" << endl; };
  7. ~c(void) { cout << "C Destructed" << endl; };
  8. };
  9. class base
  10. {
  11. public:
  12. base(void) { cout << "Base Constructed" << endl; };
  13. ~base(void) { cout << "Base Destructed" << endl; };
  14. };
  15. class derived : public base
  16. {
  17. private:
  18. c C;
  19. public:
  20. derived(void) { cout << "Derived Constructed" << endl; }
  21. ~derived(void) { cout << "Derived Destructed" << endl; };
  22. };
  23. int main(void)
  24. {
  25. derived d;
  26. return 0;
  27. }
  28. /*
  29. Base Constructed
  30. C Constructed
  31. Derived Constructed
  32. Derived Destructed
  33. C Destructed
  34. Base Destructed
  35. */