C++支持多重继承,也就是菱形继承,它是指两个子类继承了同一个父类,而又有子类同时继承了这两个子类。
#include <iostream>
using namespace std;
class A
{
public:
A(){cout << "A" << endl;}
~A(){cout << "~A" << endl;}
int a;
};
class B:virtual public A
{
public:
B(){cout << "B" << endl;}
~B(){cout << "~B" << endl;}
private:
int b;
};
class C:virtual public A
{
public:
C(){cout << "C" << endl;}
~C(){cout << "~C" << endl;}
private:
int c;
};
class D:public B,public C
{
public:
D(){cout << "D" << endl;}
~D(){cout << "~D" << endl;}
private:
int d;
};
int main()
{
D d;
d.B::a = 100;
cout << d.a << endl;
cout << d.B::a << endl;
cout << d.C::a << endl;
d.a = 10;
cout << d.a << endl;
cout << d.B::a << endl;
cout << d.C::a << endl;
return 0;
}