继承中构造和析构的顺序
-
先父母,后客人,最后自己
-
静态变量和全局变量在最开始
-
析构和构造的顺序完全相反
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class Global 7 { 8 public: 9 Global() 10 { 11 cout<< "Global()" << endl; 12 } 13 14 ~Global() 15 { 16 cout<< "~Global()" << endl; 17 } 18 }; 19 20 21 class Other 22 { 23 public: 24 Other() 25 { 26 cout<< "Other()" << endl; 27 } 28 29 ~Other() 30 { 31 cout<< "~Other()" << endl; 32 } 33 }; 34 35 class Parent 36 { 37 public: 38 Parent() 39 { 40 cout<< "Parent()" << endl; 41 } 42 43 ~Parent() 44 { 45 cout<< "~Parent()" << endl; 46 } 47 }; 48 49 class Child : public Parent 50 { 51 Other other; 52 public: 53 Child() 54 { 55 cout<< "Child()" << endl; 56 } 57 58 ~Child() 59 { 60 cout<< "~Child()" << endl; 61 } 62 }; 63 64 Global gobal; 65 66 int main() 67 { 68 Child c; //构造顺序 Global() Parent() Other() Child() 69 //析构顺序 ~Global() ~Child() Other() Parent() 70 71 return 0; 72 }