C++内存布局(一) 引子 虚继承

class A
{
public:
int a;
};

class B : virtual public A
{
public:
int b;
};

class C : virtual public A
{};

class D : public C, public B
{};

int _tmain(int argc, _TCHAR* argv[])
{
A x;
B y; // ----->这里为B时候内存是 下面1的情况
//D y; // ----->这里为D的时候y的内存如下2;
int a = 0, b = 0, c = 0;
y.b = 3;
y.a = 4;

int *y1 = (int*)(&y);
memcpy(&a, y1, 4);
memcpy(&b, y1 + 1, 4);
memcpy(&c, y1 + 2, 4);
cout << a << " " << b << " " << c <<" " << endl;
//system("pause"); //在此处加上断点
return 0;
}

1.
&y 0x0012fec0
&(y.b) 0x0012fec4
&(*(A*)(&y)) 0x0012fec8
&(*(A*)(&(y.a)) 0x0012fec8

2.
&y 0x0012febc
&(*(C*)(&y)) 0x0012febc
&(*(B*)(&y)) 0x0012fec0
&(y.b) 0x0012fec4
&(*(A*)(&(y.a)) 0x0012fec8

class A
{
public:
int a;
};

class B : virtual public A
{
public:
int b;
};

class C : virtual public A
{
public:
//int c; // 打开 3
};

class D : public C, public B
{
public:
//int d; // 打开 4
};

int _tmain(int argc, _TCHAR* argv[])
{
A x;
D y;
int a = 0, b = 0, c = 0;
y.b = 3;
y.a = 4;

int *y1 = (int*)(&y);
memcpy(&a, y1, 4);
memcpy(&b, y1 + 1, 4);
memcpy(&c, y1 + 2, 4);
cout << a << " " << b << " " << c <<" " << endl;
//system("pause"); //在此处加上断点
return 0;
}

3.
&(y.c) 0x0012febc
&y 0x0012feb8
&(*(C*)(&y)) 0x0012feb8
&(*(B*)(&y)) 0x0012fec0
&(y.b) 0x0012fec4
&(*(A*)(&(y.a)) 0x0012fec8

4.
&(y.d) 0x0012feb8
&y 0x0012feb4
&(*(C*)(&y)) 0x0012feb4
&(*(B*)(&y)) 0x0012febc
&(y.b) 0x0012fec0
&(y.c) 0x0012fec4
&(*(A*)(&(y.a)) 0x0012fec8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值