#include<iostream>
using namespace std;
class Base1
{
public:
Base1(int x):m_x(x)
{
cout<<"create base1!"<<endl;
}
~Base1()
{
cout<<"Free Base1"<<endl;
}
private:
int m_x;
};
class Base2
{
public:
Base2(int y):m_y(y)
{
cout<<"create base2!"<<endl;
}
~Base2()
{
cout<<"Free Base2"<<endl;
}
private:
int m_y;
};
class Base3
{
public:
Base3(int z):m_z(z)
{
cout<<"create base3!"<<endl;
}
~Base3()
{
cout<<"Free Base3"<<endl;
}
private:
int m_z;
};
class D:public Base2,public Base1,public Base3//父类构造顺序由这块的声明顺序决定
{
/*构造顺序只和声明顺序有关*/
public:
D(int data):Base1(data),Base2(data),Base3(data),b1(data),b2(data),b3(data)//在这块的初始化顺序和构造顺序无关
{
cout<<"create D!"<<endl;
}
~D()
{
cout<<"Free D"<<endl;
}
private:
Base1 b1;
Base2 b2;
Base3 b3;
};
void main()
{
D d(10);
}
/*
派生类构造函数各部分的执行次序为:
1-调用基类构造函数,按它们在派生类定义的先后顺序,顺序调用
2-调用成员对象的构造函数,按它们在类定义中声明的先后顺序,顺序调用
3-派生类的构造函数体中的操作
*/
/*
class Base
{
public:
Base()
{
cout<<"create base!"<<endl;
}
~Base()
{
cout<<"Free Base"<<endl;
}
private:
int x;
};
class D:public Base
{
public:
D()
{
cout<<"create D!"<<endl;
}
~D()
{
cout<<"Free D"<<endl;
}
private:
int y;
};
void main()
{
D d;
}
*/