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
多重继承与虚拟继承解析
本文通过具体的C++代码示例,深入探讨了多重继承和虚拟继承机制下对象内存布局的特点,展示了不同继承方式如何影响派生类对象的内存分配与访问。
350

被折叠的 条评论
为什么被折叠?



