C++對象模型內存布局如下: 非靜態數據成員在對象之內靜態數據成員在對象之外靜態、非靜態成員函數在對象之外類中存在虛函數時,一個類對應一個virtual table放在對象之外,對象中安插一個指針vptr指向這個表。 測試例程:
#includeusing namespace std; class A { public: int x, y; static int s; void f1() { } static void f2() { } virtual void f3() { } }; int A::s = 123; int main() { cout << "size = " << sizeof(A); return 0; }
#includeusing namespace std; class A { public: int x, y; }; class B: public A { }; class C: virtual public A { }; int main() { cout << "class B size = " << sizeof(B) << endl; cout << "class C size = " << sizeof(C) << endl; return 0; }