C++多重繼承,菱形繼承中構造函數的調用順序
C++中多重繼承不免會出現鑽石繼承,也就是繼承類的兩個基類同時又是同一個基類的繼承類,當創建一個對象的時候,他們是按照什麼樣的順序調用構造函數的呢。
如果不進行虛擬繼承:
class Base
{
public:
Base()
{
cout<<"Base默認構造函數調用"<<endl;
}
Base(int i)
{
cout<<"Base參數構造函數調用"<<endl;
cout<<i<<endl;
}
virtual ~Base(){}
};
class Base1: public Base{
public:
Base1(int i,int j=0):Base(j){
cout<<"Base1參數構造函數調用"<<endl;
cout<<i<<endl;
}
virtual ~Base1(){}
};
class Base2: public Base{
public:
Base2(int i):Base(i){
cout<<"Base2參數構造函數調用"<<endl;
cout<<i<<endl;
}
virtual ~Base2(){}
};
class Drived:public Base1,public Base2{
public:
Drived(int a,int b,int c,int d):Base1(a),Base2(b){
}
virtual ~Drived(){}
};
虛擬繼承(虛擬繼承中Base1 Base2 中對Base的構造函數調用不再起作用,Base構造函數的調用由derived類直接負責,若Drived不明確指出,則調用默認無參數的構造函數):<br><br>
class Base
{
public:
Base()
{
cout<<"Base默認構造函數調用"<<endl;
}
Base(int i)
{
cout<<"Base參數構造函數調用"<<endl;
cout<<i<<endl;
}
virtual ~Base(){}
};
class Base1: virtual public Base{
public:
Base1(int i,int j=0):Base(j){
cout<<"Base1參數構造函數調用"<<endl;
cout<<i<<endl;
}
virtual ~Base1(){}
};
class Base2: virtual public Base{
public:
Base2(int i):Base(i){
cout<<"Base2參數構造函數調用"<<endl;
cout<<i<<endl;
}
virtual ~Base2(){}
};
class Drived:public Base1,public Base2{
public:
Drived(int a,int b,int c,int d):Base1(a),Base2(b){
}
virtual ~Drived(){}
};
如果Drived類中有Base1 Base2 類型的成員函數:
class Drived:public Base1,public Base2{
public:
Base1 mem1;
Base2 mem2;
Drived(int a,int b,int c,int d):Base1(a),Base2(b),mem1(c),mem2(d){
}
virtual ~Drived(){}
};
如果在Derived類中指定Base的構造函數:
class Drived:public Base1,public Base2{
public:
Base1 mem1;
Base2 mem2;
Drived(int a,int b,int c,int d):Base1(a),Base2(b),Base(a),mem1(c),mem2(d){
}
virtual ~Drived(){}
};