且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对象内存布局 (13)——上一篇的纠正

更新时间:2022-08-28 12:50:29

下面来看看虚基类对对象内存布局的影响。虚基类的主要作用就是在所有的派生类中,保留且仅保留一份虚基类的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 = \t" << 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;
}

运行结果:

对象内存布局 (13)——上一篇的纠正

虚继承的内存分布图:

对象内存布局 (13)——上一篇的纠正