zoukankan      html  css  js  c++  java
  • 对象内存布局 (13)——上一篇的纠正

    下面来看看虚基类对对象内存布局的影响。虚基类的主要作用就是在所有的派生类中,保留且仅保留一份虚基类的suboject。

    #include <iostream>
    using namespace std;
    
    class Base
    {
    public:
        int m_base;
        Base():m_base(20){}
        virtual void vfBase_1()
        {
            cout << "This is in Base::vfBase_1()" << endl;
        }
        virtual void vfBase_2()
        {
            cout << "This is in Base::vfBase_2()" << endl;
        }
    };
    
    class Derived : public virtual Base
    {
    public:
        int m_derived;
        Derived():m_derived(10){}
        virtual void vfDerived()
        {
          cout << "This is in Derived::vfDerived()" << endl;
        }
        void vfBase_1()
        {
            cout << "This is in Derived::vfBase_1()" << endl;
        }
    };
    
    typedef void (*VFun)(void);
    
    int main(void)
    {
        Derived d;
        int **pVtab=NULL;
        pVtab=(int**)&d;
        cout << "The size of Base object = 	" << sizeof(Derived) << endl;
        cout << endl;
        cout<<"derived lst virtual function address: "<<(int*)(*((int*)(*(int*)&d) + 0))<<endl;
        cout<<"derived lst virtual function result: ";
        VFun pVF =(VFun)pVtab[0][0];
        pVF();
        cout<<endl;
        cout<<"derived 2nd virtual function address: "<<(int*)(*((int*)(*(int*)&d) + 1))<<endl;
        cout<<"derived 2nd virtual function result: ";
        pVF = (VFun)pVtab[0][1];
        pVF();
        cout<<endl;
        cout<<"virtual table end flags: "<<pVtab[0][2]<<endl;
        cout<<endl;
    
        cout<<"derived data member:";
        cout<<(int)*((int*)&d+1)<<endl;
    
        cout<<"base lst virtual function address: "<<(int*)pVtab[2][0]<<endl;
        cout<<"base lst virtual function result: ";
        pVF = (VFun)pVtab[2][0];
        pVF();
        cout<<endl;
        //转换为int*就代表虚函数的地址
        cout<<"base 2nd virtual function address: "<<(int*)(*((int*)(*((int*)&d+2)) + 1))<<endl;
        cout<<"base 2nd virtual function result: ";
        //转换为vFun代表虚函数的函数指针
        pVF = (VFun)(*((int*)(*((int*)&d+2)) + 1));
        pVF();
        cout<<endl;
        cout<<"virtual table end flags: "<<(*((int*)(*((int*)&d+2)) + 2))<<endl;
        cout<<endl;
        cout<<"base data member:";
        cout<<(int)pVtab[3]<<endl;
        return 0;
    }

    运行结果:

    虚继承的内存分布图:

  • 相关阅读:
    (转载)Android xml资源文件中@、@android:type、@*、?、@+引用写法含义以及区别
    Android事件分发和消费机制(转载)
    Android动画及滑动事件冲突解决(转载)
    写在学习Oracle之前
    laragon yii
    ubuntu使用bower install问题汇总
    LNMP架构下访问php页面出现500错误
    form表单提交无页面刷新(非js)
    Firefox浏览器无法安装插件的解决
    完美解决 Ubuntu 下 Sublime Text 2配置搜狗拼音输入法
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4093463.html
Copyright © 2011-2022 走看看