码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-11-12 22:35:12      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   sp   div   on   

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

运行结果:

bubuko.com,布布扣

虚继承的内存分布图:

bubuko.com,布布扣

 

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

标签:style   blog   http   io   color   os   sp   div   on   

原文地址:http://www.cnblogs.com/wuchanming/p/4093463.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!