50-C++對象模型分析(上)
阿新 • • 發佈:2018-06-13
依次 分析 sin bsp get 本質 過程 ons 結構體
回歸本質
class是一種特殊的struct:
? 在內存中class依舊可以看作變量的集合
? class與struct遵循相同的內存對其規則
? class中的成員函數與成員變量是分開存放的:(1)每個對象有獨立的成員變量(2)所有對象共享類中的成員函數
值得思考的問題?
【範例代碼】對象內存布局初探
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class A { 7 int i; 8 int j; 9 charc; 10 double d; 11 public: 12 void print() { 13 cout << "i = " << i << ", " 14 << "j = " << j << ", " 15 << "c = " << c << ", " 16 << "d = " << d << endl; 17 } 18 }; 19 20struct B { 21 int i; 22 int j; 23 char c; 24 double d; 25 }; 26 27 int main(int argc, const char* argv[]) { 28 A a; 29 30 cout << "sizeof(A) = " << sizeof(A) << endl; // 20 bytes 31 cout << "sizeof(a) = " << sizeof(a) << endl; 32 cout << "sizeof(B) = " << sizeof(B) << endl; // 20 bytes 33 34 a.print(); 35 36 B* p = reinterpret_cast<B*>(&a); 37 38 p->i = 1; 39 p->j = 2; 40 p->c = ‘c‘; 41 p->d = 3; 42 43 a.print(); 44 45 p->i = 100; 46 p->j = 200; 47 p->c = ‘C‘; 48 p->d = 3.14; 49 50 a.print(); 51 52 return 0; 53 }
C++對象模型分析
運行時的對象退化為結構體的形式:
? 所有成員變量在內存中依次排布
? 成員變量間可能存在內存間隙
? 可以通過內存地址直接訪問成員變量
? 訪問權限關鍵字在運行時失效
? 類中的成員函數位於代碼段中
? 調用成員函數時對象地址作為參數隱式傳遞
? 成員函數通過對象地址訪問成員變量
? C++語法規則隱藏了對象地址的傳遞過程
【範例代碼】對象本質分析
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class Demo { 7 int mi; 8 int mj; 9 public: 10 Demo(int i, int j) { 11 mi = i; 12 mj = j; 13 } 14 15 int getI() { 16 return mi; 17 } 18 19 int getJ() { 20 return mj; 21 } 22 23 int add(int value) { 24 return mi + mj + value; 25 } 26 }; 27 28 int main(int argc, const char* argv[]) { 29 Demo d(1, 2); 30 31 cout << "sizeof(d) = " << sizeof(d) << endl; 32 cout << "d.getI() = " << d.getI() << endl; 33 cout << "d.getJ() = " << d.getJ() << endl; 34 cout << "d.add(3) = " << d.add(3) << endl; 35 36 return 0; 37 }
50-C++對象模型分析(上)