代碼1:
1 #include <cstdio> 2 #include <iostream> 3 4 using namespace std; 5 6 class A{ 7 public: 8 A(){ 9 cout<<"A"<<endl; 10 } 11 }; 12 class B{ 13 public: 14 B(){ 15 cout<<"B"<<endl; 16 } 17 }; 18 class C:public B,public A{ 19 //class C:public A,public B{ 20 public: 21 C(){ 22 cout<<"C"<<endl; 23 } 24 }; 25 int main(){ 26 27 C c; 28 return 0; 29 }
輸出:
B A C
分析:
多重繼承與單繼承類似,也是先執行基類構造函數。多個基類之間,則按照派生類聲明時從左到右執行。
代碼2:
1 #include <cstdio> 2 #include <iostream> 3 4 using namespace std; 5 6 class A{ 7 public: 8 A(){ 9 cout<<"A"<<endl; 10 } 11 }; 12 class B{ 13 public: 14 B(){ 15 cout<<"B"<<endl; 16 } 17 }; 18 class C:public B,public A{ 19 //class C:public A,public B{ 20 public: 21 A a; 22 C(){ 23 cout<<"C"<<endl; 24 } 25 }; 26 int main(){ 27 28 C c; 29 return 0; 30 }
輸出:
B A A C
分析:
執行順序:基類構造函數->初始化成員變量->派生類構造函數
