- 如果一個派生類從多個基類派生,而這些基類又有一個共同的基類,則在對該基類中聲明的名字進行訪問時,可能產生二義性
- 如果在多條繼承路徑上有一個公共的基類,那麼在繼承路徑的某處匯合點,這個公共基類就會在派生類的對象中產生多個基類子對象
- 要使這個公共基類在派生類中只產生一個子對象,必須對這個基類聲明爲虛繼承,使這個基類成爲虛基類。
- 虛繼承聲明使用 關鍵字 virtual
#include <iostream>
using namespace std;
class Base
{
public:
Base(int b)
{
cout << "Base 構造函數被調用" << endl;
}
public:
int b;
};
class Base1:virtual public Base
{
public:
Base1(int b1) : Base(b1)
{
this->b1 = b1;
cout << "Base1 構造函數被調用" << endl;
}
void printB1()
{
cout << "b1 : " << this->b1 << endl;
}
private:
int b1;
};
class Base2 : virtual public Base
{
public:
Base2(int b2) : Base(b2)
{
this->b2 = b2;
cout << "Base2 構造函數被調用" << endl;
}
void printB2()
{
cout << "b2 : " << this->b2 << endl;
}
private:
int b2;
};
class A : public Base1, public Base2
{
public:
A(int b1, int b2, int a) : Base1(b1), Base2(b2), Base(b1)
{
this->a = a;
cout << "A 構造函數被調用" << endl;
}
void printA()
{
cout << "a : " << this->a << endl;
}
private:
int a;
};
int main(int argc, char *argv[])
{
{
A a(1,2,3);
a.printA();
a.printB1();
a.printB2();
a.b = 200;
}
return 0;
}