對象記憶體布局 (1)

來源:互聯網
上載者:User

內容概要:

滿足下面2個條件時,

1. 父類有虛函數,子類無虛函數(即無虛函數重寫或無虛函數覆蓋)

2. 非虛繼承

類對象之記憶體布局

 

前述相關內容參考:

1. http://blog.csdn.net/pathuang68/archive/2009/04/20/4096088.aspx

2. http://blog.csdn.net/pathuang68/archive/2009/04/21/4096429.aspx

3. http://blog.csdn.net/pathuang68/archive/2009/04/21/4096521.aspx

 

Base類中有兩個虛函數vfBase_1()、vfBase_2()和一個整形成員變數m_base, Derived類中有一個整形成員變數m_derived,二者的關係如下:

 

代碼如下:

#include <iostream>

using namespace std;

 

class Base

{

public:

         int m_base;

         inline virtual void vfBase_1()

         {

                   cout << "This is in Base::vfBase_1()" << endl;

         }

 

         inline virtual void vfBase_2()

         {

                   cout << "This is in Base::vfBase_2()" << endl;

         }

};

 

class Derived : public Base

{

public:

         int m_derived;

};

 

typedef void (*VFun)(void);

 

// 改為template形式,因為不能確定傳進來的參數是Base類型的指標還是Derived類型的指標

template<typename T>

VFun virtualFunctionPointer(T* b, int i)

{

     return (VFun)(*((int*)(*(int*)b) + i));

}

 

int main(void)

{

         Derived d;

         cout << "The size of Base object = /t" << sizeof(Derived) << endl;

 

         cout << endl;

 

         int i = 0;

         while(virtualFunctionPointer(&d, i))

         {

                   VFun pVF = virtualFunctionPointer(&d, i++);

                   pVF();

         }

         return 0;

}

運行結果如下:

 

 

Derived對象的memory layout圖解如下:

 

後篇:http://blog.csdn.net/pathuang68/archive/2009/04/23/4101977.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.