#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;
}
*/