C++類的記憶體分佈
阿新 • • 發佈:2020-07-04
C++一般類的記憶體分佈
一下都是在x64下進行的編譯
1、空類
2、無繼承、無虛擬函式類
3、無繼承、有虛擬函式類
4、有繼承、有虛擬函式類
C++繼承類的記憶體分佈
C++多重繼承時的記憶體分佈
#include <iostream> using namespace std; class A { public: int a; }; class B1 : public A { public: int b1; }; class B2 : public A { public: int b2; }; classC : public B1, public B2 { public: int c1; }; int main() { cout << "A_size=" << sizeof(A) << endl; cout << "B1_size=" << sizeof(B1) << endl; cout << "B2_size=" << sizeof(B2) << endl; cout << "C_size=" << sizeof(C) << endl; cout << "end..." << endl; system("pause"); return 0; }
類A、B1、B2的記憶體分佈
類C的記憶體分佈
C++類虛繼承時的記憶體分佈---->虛繼承解決二義性的問題
#include <iostream> using namespace std; class A { public: int a; }; class B1 : virtual public A { public: int b1; };class B2 : virtual public A { public: int b2; }; class C : public B1, public B2 { public: int c1; }; int main() { C c1; c1.b1 = 100; c1.b2 = 200; c1.c1 = 300; c1.a = 500; //虛繼承使得成員變數a只有一份拷貝,通過虛指標可以確定地址 cout << "A_size=" << sizeof(A) << endl; cout << "B1_size=" << sizeof(B1) << endl; cout << "B2_size=" << sizeof(B2) << endl; cout << "C_size=" << sizeof(C) << endl; cout << "end..." << endl; system("pause"); return 0; }
類A和B1的記憶體分佈
類B2的記憶體分佈
類C的記憶體分佈