虚拟菱形继承
如果我们有如下继承层次:
class B{...}
class B1: virtual public B{...}
class B2: virtual public B{...}
class D : public B1,public B2{...}
类图如下所示:
菱形虚拟继承下,最派生类D类的对象模型又有不同的构成了。在D类对象的内存构成上,有以下几点:
- 在D类对象内存中,基类出现的顺序是:先是B1(最左父类),然后是B2(次左父类),最后是B(虚祖父类)
- D类对象的数据成员id放在B类前面,两部分数据依旧以0来分隔。
- 编译器没有为D类生成一个它自己的vptr,而是覆盖并扩展了最左父类的虚基类表,与简单继承的对象模型相同。
- 超类B的内容放到了D类对象内存布局的最后。
菱形虚拟继承下的C++对象模型为:

下面使用代码加以验证:
int main()
{
D d;
cout << "D对象内存大小为:" << sizeof(d) << endl;
//取得B1的虚函数表
cout << "[0]B1::vptr";
cout << "\t地址:" << (int *)(&d) << endl;
//输出虚表B1::vptr中的函数
for (int i = 0; i<3; ++i)
{
cout << " [" << i << "]";
Fun fun1 = (Fun)*((int *)*(int *)(&d) + i);
fun1();
cout << "\t地址:\t" << *((int *)*(int *)(&d) + i) << endl;
}
//[1]
cout << "[1]B1::vbptr ";
cout << "\t地址:" << (int *)(&d) + 1 << endl; //虚表指针的地址
//输出虚基类指针条目所指的内容
for (int i = 0; i < 2; i++)
{
cout << " [" << i << "]";
cout << *(int *)((int *)*((int *)(&d) + 1) + i);
cout << endl;
}
//[2]
cout << "[2]B1::ib1=" << *(int*)((int *)(&d) + 2);
cout << "\t地址:" << (int *)(&d) + 2;
cout << endl;
//[3]
cout << "[3]B2::vptr";
cout << "\t地址:" << (int *)(&d) + 3 << endl;
//输出B2::vptr中的虚函数
for (int i = 0; i<2; ++i)
{
cout << " [" << i << "]";
Fun fun1 = (Fun)*((int *)*((int *)(&d) + 3) + i);
fun1();
cout << "\t地址:\t" << *((int *)*((int *)(&d) + 3) + i) << endl;
}
//[4]
cout << "[4]B2::vbptr ";
cout << "\t地址:" << (int *)(&d) + 4 << endl; //虚表指针的地址
//输出虚基类指针条目所指的内容
for (int i = 0; i < 2; i++)
{
cout << " [" << i << "]";
cout << *(int *)((int *)*((int *)(&d) + 4) + i);
cout << endl;
}
//[5]
cout << "[5]B2::ib2=" << *(int*)((int *)(&d) + 5);
cout << "\t地址: " << (int *)(&d) + 5;
cout << endl;
//[6]
cout << "[6]D::id=" << *(int*)((int *)(&d) + 6);
cout << "\t地址: " << (int *)(&d) + 6;
cout << endl;
//[7]
cout << "[7]值=" << *(int*)((int *)(&d) + 7);
cout << "\t\t地址:" << (int *)(&d) + 7;
cout << endl;
//间接父类
//[8]
cout << "[8]B::vptr";
cout << "\t地址:" << (int *)(&d) + 8 << endl;
//输出B::vptr中的虚函数
for (int i = 0; i<2; ++i)
{
cout << " [" << i << "]";
Fun fun1 = (Fun)*((int *)*((int *)(&d) + 8) + i);
fun1();
cout << "\t地址:\t" << *((int *)*((int *)(&d) + 8) + i) << endl;
}
//[9]
cout << "[9]B::id=" << *(int*)((int *)(&d) + 9);
cout << "\t地址: " << (int *)(&d) +9;
cout << endl;
getchar();
}
查看运行结果:
