C++對象記憶體布局--⑩GCC編譯器--虛擬繼承--菱形繼承
//GCC編譯器--虛擬繼承--菱形繼承.cpp//2010.8.19//GCC編譯器#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 記憶體布局:" << endl; for (int i = 0; i != sizeof(obj)/4; ++i) { cout << p[i] << endl; } cout << endl; typedef void (*fun)(void*pThis);//非常重要/*通過虛函數表調用函數*//*第一個虛函數表指標。BaseA*/((fun)(p[0][0]))(p);((fun)(p[0][1]))(p);//頭兩個是BaseA的((fun)(p[0][2]))(p);((fun)(p[0][3]))(p);//後兩個是Derived的/*第二個虛函數表指標。BaseB*/cout << endl;((fun)(p[2][0]))(p+2);/*第三個虛函數表指標。Base*/ cout << endl;((fun)(p[5][0]))(p+5);((fun)(p[5][1]))(p+5); return 0;}/*Derived obj 記憶體布局:0x472d0c0x140x472d280x1e0x280x472d3c0xaBaseA::showA() 20BaseA::testA() 20Derived::show() 40Derived::test() 40BaseB::showB() 30Derived::show() 40BaseA::testA() 20*/