C++對象記憶體布局–③測試多繼承中衍生類別的虛函數在哪一張虛函數表中

來源:互聯網
上載者:User

C++對象記憶體布局--③測試多繼承中衍生類別的虛函數在哪一張虛函數表中

測試2:證明衍生類別的虛函數的地址跟第一基類的虛函數地址儲存在同一張虛函數表中。

   衍生類別有多少個擁有虛函數的基類,衍生類別對象就有多少個指向虛函數表的指標。

//測試多繼承中衍生類別的虛函數在哪一張虛函數表中.cpp//2010.8.18//測試證明衍生類別的虛函數的地址跟第一基類的虛函數地址儲存在同一張虛函數表中。衍生類別有多少個擁有虛函數的基類,衍生類別對象就有多少個指向虛函數表的指標。//VS編譯器#include <iostream>#include <string>using   namespace   std;//////////////////////////////////////////////////////////////////class Base1{    public:        Base1(int a1 = 10):a1(a1)        {            cout << "Base1::Base1()" << endl;        }        virtual void show1()        {            cout << "Base1::show1()" << endl;        }    private:        int a1;};//////////////////////////////////////////////////////////////////class Base2{    public:        Base2(int a2 = 20):a2(a2)        {            cout << "Base2::Base2()" << endl;        }        virtual void show2()        {            cout << "Base2::show2()" << endl;        }    private:        int a2;};//////////////////////////////////////////////////////////////////class Derived : public Base1, public Base2{    public:        Derived(int a3 = 100):a3(a3)        {            cout << "Derived::Derived()" << endl;        }        virtual void show3()        {            cout << "Derived::show3()" << endl;        }    private:        int a3;};//////////////////////////////////////////////////////////////////int main(){    Derived aobj;    int** p = (int**)&aobj;    typedef void (__thiscall *fun)(void*pThis);//非常重要    cout << "衍生類別對象大小 = " << sizeof(aobj) << endl;    cout << "衍生類別對象記憶體布局:" << endl;    /*根據輸出可以發現:其中成員變數的值分別為0x0A、0x14、0x64,另外的兩個為虛函數表指標*/    for (int i = 0; i != sizeof(aobj)/4; ++i)    {        cout << "0x" << p[i] << endl;    }    /*從輸出可以證明衍生類別的虛函數地址跟第一基類的虛函數地址儲存在一起*/    cout << "虛函數表指標->虛函數表->函數調用:" << endl;    ((fun)(p[0][0]))(p);//Base1::show1()    ((fun)(p[0][1]))(p);//Derived::show3()    ((fun)(p[2][0]))(p+2);//Base2::show2()    system("pause");    return 0;}/*Base1::Base1()Base2::Base2()Derived::Derived()衍生類別對象大小 = 20衍生類別對象記憶體布局:0x0041C2540x0000000A0x0041C24C0x000000140x00000064虛函數表指標->虛函數表->函數調用:Base1::show1()Derived::show3()Base2::show2()請按任意鍵繼續. . .*/

 

聯繫我們

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