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是否往高方向尋找和往地方向尋找所找到的都是虛基類表呢?*/