1.执行顺序
#include<iostream>
using namespace std;
class A
{
private:
int x;
public:
A(int i){x=i;cout<<"it's constructing A class"<<endl;}
void showA(){cout<<"it's performance showA function"<<endl;}
~A(){cout<<"it's destructing A class"<<endl;}
};
class B
{
public:
B(){cout<<"it's constructing B class"<<endl;}
void showB(){cout<<"it's performance showB function"<<endl;}
~B(){cout<<"it's destructing B class"<<endl;}
};
class C:public A,public B
{
private:
A a;
B b;
public:
C(int y1,int y2):A(y1),a(y2)
{cout<<"it's constructing C class"<<endl;}
void showC()
{
showA();
showB();
cout<<"it's performance showC function"<<endl;
}
~C(){cout<<"it's destructing C class"<<endl;}
};
int main()
{
C c(1,2);
c.showC();
return 0;
}
演示结果:
2.多继承的派生类的构造函数的注意事项
1.当派生类是多继承时,要观察他继承的所有基类,只要有一个基类没有无参的构造函数,这个多继承的派生类就必须有构造函数且必须使用初始化成员列表对那个没有无参构造函数的基类进行初始化,要是该基类的对象作为派生类的私有数据成员(即内嵌对象),也要在派生类的构造函数中对其初始化。例如上面例题里派生类C对基类A的操作