代码1:
#include <cstdio>
#include <iostream> using namespace std; class A{
public:
A(){
cout<<"A"<<endl;
}
};
class B{
public:
B(){
cout<<"B"<<endl;
}
};
class C:public B,public A{
//class C:public A,public B{
public:
C(){
cout<<"C"<<endl;
}
};
int main(){ C c;
return ;
}
输出:
B
A
C
分析:
多重继承与单继承类似,也是先执行基类构造函数。多个基类之间,则按照派生类声明时从左到右执行。
代码2:
#include <cstdio>
#include <iostream> using namespace std; class A{
public:
A(){
cout<<"A"<<endl;
}
};
class B{
public:
B(){
cout<<"B"<<endl;
}
};
class C:public B,public A{
//class C:public A,public B{
public:
A a;
C(){
cout<<"C"<<endl;
}
};
int main(){ C c;
return ;
}
输出:
B
A
A
C
分析:
执行顺序:基类构造函数->初始化成员变量->派生类构造函数