手机版
你好,游客 登录 注册
背景:
阅读新闻

C++对象模型详解

[日期:2015-12-20] 来源:Linux社区  作者:QG-whz [字体:大 中 小]

虚拟菱形继承

如果我们有如下继承层次:

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();
}
 

查看运行结果:

linux
相关资讯       C++  C++对象模型  对象模型 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款