繼承和組合混搭的情況下,構造和析構函數的調用順序
阿新 • • 發佈:2018-01-30
組合 log class urn std 調用父類 parent clas 父類
繼承和組合混搭的情況下:
構造時,先調用父類的構造函數(如果父類還有父類,先執行父類的父類的構造函數,在執行父類的構造函數),再調用組合對象的構造函數,最後調用自己的構造函數;
析構時,先調用自己的析構函數,再調用組合對象的析構函數,最後調用父類的析構函數(如果父類還有父類,先執行父類的析構函數,再執行父類的父類的析構函數)。
例如下面一段代碼:
1 #include<iostream> 2 using namespace std; 3 4 class Object 5 { 6 public: 7 Object(int _x,int_y):x(_x),y(_y){cout<<"Object的構造函數"<<x<<" "<<y<<endl;} 8 ~Object(){cout<<"Object的析構函數"<<x<<" "<<y<<endl;} 9 10 private: 11 int x; 12 int y; 13 }; 14 15 16 17 18 class Parent:public Object 19 { 20 public: 21 Parent(int _a,int_b):Object(1,2),a(_a),b(_b){cout<<"Parent的構造函數"<<endl;} 22 ~Parent(){cout<<"Parent的析構函數"<<endl;} 23 24 private: 25 int a; 26 int b; 27 }; 28 29 class Child:public Parent 30 { 31 public: 32 Child(int _a,int _b,int _c):Parent(_a,_b),obj(3,4),c(_c) 33 { 34 cout<<"Child的構造函數"<<endl; 35 } 36 ~Child(){cout<<"Child的析構函數"<<endl;} 37 38 protected: 39 Object obj; 40 41 private: 42 int c; 43 }; 44 45 int main() 46 { 47 Child c(1,2,3); 48 49 return 0; 50 }
代碼的執行結果是:
Object的構造函數1 2
Parent的構造函數
Object的構造函數3 4
Child的構造函數
Child的析構函數
Object的析構函數3 4
Parent的析構函數
Object的析構函數1 2
繼承和組合混搭的情況下,構造和析構函數的調用順序