现在的位置: 首页 > 综合 > 正文

虚继承–内存布局

2012年08月30日 ⁄ 综合 ⁄ 共 1327字 ⁄ 字号 评论关闭
#include<iostream>
#include<memory.h>
#include<assert.h>

using namespace std;
class A
{
    char k[3];
public:
    A()
    {
        k[0]='1';
        k[1]='2';
        k[2]='3';
    }
    virtual void aa()
    {
        cout<<"this is A->aa()"<<endl;
    };
};
class B : public A
{
    char j[3];
public:
    B()
    {
        j[0]='4';
        j[1]='5';
        j[2]='6';
    }
    virtual void bb()
    {
        cout<<"this is B-bb()"<<endl;
    };
};
class C:public B
{
    char i[3];
public:
    C()
    {
        i[0]='7';
        i[1]='8';
        i[2]='9';
    }
    virtual void cc()
    {
        cout<<"this is C->cc()"<<endl;
    };
};


int main()
{
    A a;
    B b;
    C c;
    typedef void(*fun)(void);
    fun pf=NULL;
    pf=(fun)*((int *)*(int *)(&a));
    pf();//this is A->aa()
    pf=(fun)*((int*)*(int *)(&b));
    pf();
    pf=(fun)*((int*)*((int *)(&b))+1);
    pf();//this is B->bb()
    pf=(fun)*((int*)*((int*)(&b)+3));
    pf();//this is A->aa()
    pf=(fun)*((int*)*(int *)(&c));
    pf();//this is A->aa()
    pf=(fun)*((int*)*((int *)(&c))+1);
    pf();//this is B->bb()
    pf=(fun)*((int*)*((int *)(&c))+2);
    pf();//this is C->cc();
    pf=(fun)*((int*)*((int*)(&c)+4));
    pf();//this is A->aa()
    pf=(fun)*((int*)*((int*)(&c)+4)+1);
    pf();//this is B->bb()
    cout<<"sizeof (A)"<<sizeof(A)<<endl; //8
    cout <<"sizeof(B)"<<sizeof(B)<<endl; //12
    cout<<"sizeof(C)"<<sizeof(C)<<endl;  //16

    return 0;
}
/******** 内存结构图 ******/
/****
&a 8 字节
0x22ff18: 98 2b 47 00 31 32 33 7f | 00 60 fd 7f 00 00 00 00
0x22ff28: 68 ff 22 00 b6 10 40 00 | 01 00 00 00 38 10 64 00
&b 16 字节
0x22ff0c: a8 2b 47 00 31 32 33 34 | 35 36 65 00 98 2b 47 00
0x22ff1c: 31 32 33 7f 00 60 fd 7f | 00 00 00 00 68 ff 22 00
&c 24 字节
0x22fefc: 62 11 e8 75 bc 5b ed 75 | 80 33 41 00 28 ff 22 00
0x22ff0c: a8 2b 47 00 31 32 33 34 | 35 36 65 00 98 2b 47 00


***/

抱歉!评论已关闭.