标签:
代码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
分析:
执行顺序:基类构造函数->初始化成员变量->派生类构造函数
标签:
原文地址:http://www.cnblogs.com/hu983/p/5524682.html