C++對象記憶體布局–⑨VS編譯器–虛擬繼承–菱形繼承

來源:互聯網
上載者:User

C++對象記憶體布局--⑨VS編譯器--虛擬繼承--菱形繼承

//VS編譯器--虛擬繼承--菱形繼承.cpp//2010.8.19//VS編譯器#include <iostream>using namespace std;////////////////////////////////////////////////////////////////class Base{    public:        Base(int a = 10):a(a)        {        }        virtual void show()        {            cout << "Base::show()" << "\t" << a << endl;        }        virtual void testA()        {            cout << "Base::testA()" <<"\t" << a << endl;        }    private:        int a;};////////////////////////////////////////////////////////////////class BaseA : virtual public Base{    public:        BaseA(int b = 20):b(b)        {        }        virtual void showA()        {            cout << "BaseA::showA()" << "\t" << b << endl;        }        void testA()        {            cout << "BaseA::testA()" << "\t" << b << endl;        }    private:        int b;};////////////////////////////////////////////////////////////////class BaseB : virtual public Base{    public:        BaseB(int c = 30):c(c)        {        }        virtual void showB()        {            cout << "BaseB::showB()" << "\t" << c << endl;        }    private:        int c;};////////////////////////////////////////////////////////////////class Derived : public BaseA, public BaseB{    public:        Derived(int d = 40):d(d)        {        }        virtual void show()        {            cout << "Derived::show()" << "\t" << d << endl;        }        virtual void test()        {            cout << "Derived::test()" << "\t" << d << endl;        }    private:        int d;};////////////////////////////////////////////////////////////////int main(){    Derived obj;    int** p = (int**)&obj;    cout << "Derived obj sizeof = " << sizeof(obj) << endl;    cout << "Derived obj 記憶體布局:" << endl;    for (int i = 0; i != sizeof(obj)/4; ++i)    {        cout << p[i] << endl;    }    cout << endl;   typedef void (__thiscall *fun)(void*pThis);//非常重要/*通過虛函數表調用函數第一個虛函數表指標。BaseA*/((fun)(p[0][0]))(p);((fun)(p[0][1]))(p);//第二個虛函數表指標。BaseBcout << endl;((fun)(p[3][0]))(p+3);//第三個虛函數表指標。Base    cout << endl;((fun)(p[8][0]))(p+8);((fun)(p[8][1]))(p+8);system("pause");    return 0;}/*Derived obj sizeof = 40Derived obj 記憶體布局:0041A2000041A210000000140041A1F80041A2080000001E00000028000000000041A1EC0000000ABaseA::showA()  20Derived::test() 40BaseB::showB()  30Derived::show() 40BaseA::testA()  20*/
相關文章

聯繫我們

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