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

    运行结果:

    虚继承的内存分布图:

  • 相关阅读:
    子类调用父类被重写的方法
    Linux下编译出现undefined reference to ‘pthread_create’问题解决
    CRC校验8
    嵌入式C语言查表法
    Static关键字,遇到的问题_1
    java中方法的参数传递机制_一个对象被当作参数传递到一个方法后
    String使用equals和==比较的区别
    如何导入XML数据 (python3.6.6区别于python2 环境)
    0xx_PHP核心01
    PHP_MVC设计模式02
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4093463.html
Copyright © 2011-2022 走看看