代码:
#include<iostream>
using namespace std;
class A
{
public:
int n;
};
class B:public A {}; // 声明A为公有继承的虚基类
class C:public A {}; // 声明A为公有继承的虚基类
class D:public B,public C
{
public:
int getn() {return B::n;}
};
int main()
{
D d;
d.B::n=10;
d.C::n=20;
cout<<d.getn()<<endl;
return 0;
}
运行结果:
学习心得:
d.B::n=10;是引用d对象中的基类B的数据成员n,d.C::n=20;是引用d对象中的基类C的数据成员n,因为类B和类C都声明A为公有继承的虚基类,所以d.getn()是调用类A的成员函数,然后return B::n;输出类B的数据成员n。