C++記憶體布局(一) 引子 虛繼承

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.