C++對象記憶體布局–⑤GCC編譯器–單個虛擬繼承

來源:互聯網
上載者:User

C++對象記憶體布局--⑤GCC編譯器--單個虛擬繼承

  測試GNU的GCC編譯器在處理虛擬繼承上跟VS不同的地方。衍生類別的虛函數表跟虛基類表合并。

//GCC編譯器--單個虛擬繼承.cpp//2010.8.18//虛基類表到底是那個?,還是說衍生類別的虛函數表的上邊和下邊都是?//GCC編譯器#include <iostream>using   namespace std;//////////////////////////////////////////////////////////////////class Base{    public:        Base(int a = 10):a(a)        {            cout << "Base::Base()" << endl;        }        virtual void show1()        {            cout << "Base::show1()" << endl;            cout << a << endl;        }    private:        int a;};//////////////////////////////////////////////////////////////////class Derived : virtual public Base{    public:        Derived(int b = 100):b(b)        {            cout << "Derived::derived()" << endl;        }        virtual void show2()        {            cout << "Derived::show2()" << endl;            cout << b << endl;        }    private:        int b;};//////////////////////////////////////////////////////////////////int main(){    Derived obj;    int** p = (int**)&obj;    cout << "虛擬繼承了基類的衍生類別的對象記憶體布局:" <<endl;    for (int i = 0; i != sizeof(obj)/4; ++i)    {        cout << p[i] << endl;    }     typedef void (*fun)(void*pThis);//this指標非常重要    cout << endl << "第一虛函數表第一項,虛函數Derived::show2()地址:" << (int*)p[0][0] << endl;    ((fun)(p[0][0]))(p);    cout << "第二虛函數表第一項,虛函數Base::show1()地址   :" << (int*)p[2][0] << endl;    ((fun)(p[2][0]))(p+2);    cout << endl << "衍生類別虛函數表指標往低地址方向定址:" << endl;    cout << "p[0][-1] = " << (int*)p[0][-1] << endl;    cout << "p[0][-2] = " << (int*)p[0][-2] << endl;    cout << "p[0][-3] = " << (int*)p[0][-3] << endl;    cout << endl << "衍生類別虛函數表指標往高地址方向定址:" << endl;    cout << "p[0][0] = " << (int*)p[0][0] << "(這個是show2()函數地址)" << endl;    cout << "p[0][1] = " << (int*)p[0][1] << endl;    cout << "p[0][2] = " << (int*)p[0][2] << endl;    cout << "p[0][3] = " << (int*)p[0][3] << endl;    cout << endl << "是否往高方向尋找和往地方向尋找所找到的都是虛基類表呢?" << endl;    //system("pause");    return 0;}/*Base::Base()Derived::derived()虛擬繼承了基類的衍生類別的對象記憶體布局:0x472d4c0x640x472d5c0xa第一虛函數表第一項,虛函數Derived::show2()地址:0x41cd50Derived::show2()100第二虛函數表第一項,虛函數Base::show1()地址   :0x41ccbcBase::show1()10衍生類別虛函數表指標往低地址方向定址:p[0][-1] = 0x471388p[0][-2] = 0p[0][-3] = 0x8衍生類別虛函數表指標往高地址方向定址:p[0][0] = 0x41cd50(這個是show2()函數地址)p[0][1] = 0p[0][2] = 0xfffffff8p[0][3] = 0x471388是否往高方向尋找和往地方向尋找所找到的都是虛基類表呢?*/
相關文章

聯繫我們

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