C++ 类的内存布局
测试代码: #include <iostream> using namespace std; struct A{ long long a = 10; virtual void fa(){ cout << "A::fa()\n"; } virtual void faa(){ cout << "A::faa()\n"; } }; // 如果是虚继承,虚基类被放在了派生类的后面,每个基类都有自己的虚函数表指针存储单元,如果虚基类没有虚函数,则虚基类的虚函数表指针为 0 // 如果是非虚继承,基类在派生类的前面,每个基类都有自己的虚函数表指针存储单元,除了第一个基类(派生类与第一个基类共用一个存储单元) struct E: virtual A{ long long e = 2; virtual void fa(){ cout << "E::fa()\n"; } virtual void fe(){ cout << "E::fe()\n"; } }; int main() { typedef void(*FUNC)(); E e; cout << sizeof(e) << endl; long long* addr = (long long*)&e; long long* vfptre = (long long*)*(addr + 0); int eval = (int)*(addr + 1); cout << eval << endl; long long* vfptra = (long long*)*(addr + 2); int aval = (int)*(addr + 3); cout << aval << endl; cout << "---------------\n"; long long* faptr = (long long*)*(vfptre + 0); (FUNC(faptr))(); long long* feptr = (long long*)*(vfptre + 1); (FUNC(feptr))(); cout << "---------------\n"; long long* faptra = (long long*)*(vfptra + 0); // (FUNC(faptra))(); // 如果虚基类的虚函数被重写,此处则无法再如此执行 long long* faaptra = (long long*)*(vfptra + 1); (FUNC(faaptra))(); return 0; } 输出:...