C++对象内存布局--⑥GCC编译器-虚拟继承的虚基类表可能有两个
//证明GCC编译器-单个虚拟继承的虚基类表有两个.cpp //2010.8.18 //派生类不定义虚函数,所以派生类对象的第一个位置(指向虚基类表的指针)所指向的表为虚基类表。这样定义更容易辨认到底是不是有两个虚基类表 //事实证明,指向虚基类表的指针,向上寻址和向下寻址所得到的值,都是指向本类或者虚基类的偏移值,只不过偏移的方向不同而已。 //负方向寻址能够获得的值:虚基类实例地址 - 虚基类表指针地址; //正方向寻址能够获得的值:虚基类表指针地址 - 虚基类实例地址; //GCC编译器 #include <iostream> using namespace std; ////////////////////////////////////////////////////////////////// class Base { public: Base(int a = 10):a(a) { } virtual void show() { cout << "Base::show()" << endl; } private: int a; }; ////////////////////////////////////////////////////////////////// class Derived : virtual public Base { public: Derived(int b = 20):b(b) { } void show2() { cout << "Derived::show2()" << endl; } private: int b; }; ////////////////////////////////////////////////////////////////// int main() { Derived dobj; int **p = (int**)&dobj; for (int i = 0; i != sizeof(dobj)/4; ++i) { cout << p[i] << endl; } cout << endl; cout << "负值寻址" << endl; cout << "p[0][-1] = " << p[0][-1] << endl; cout << "p[0][-2] = " << p[0][-2] << endl; cout << "p[0][-3] = " << p[0][-3] << endl; cout << endl << "正值寻址" << endl; cout << "p[0][0] = " << p[0][0] << endl; cout << "p[0][1] = " << p[0][1] << endl; cout << "p[0][2] = " << p[0][2] << endl; return 0; } /* 0x472bec 0x14 0x472bf8 0xa 负值寻址 p[0][-1] = 4657704 p[0][-2] = 0 p[0][-3] = 8 正值寻址 p[0][0] = 0 p[0][1] = -8 p[0][2] = 4657704 */