• 在C++編譯器的內部類能夠理解爲結構體ios
• 子類是由父類成員疊加子類新成員獲得的數據結構
【範例代碼】繼承對象模型初探函數
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class Demo { 7 protected: 8 int mi; 9 int mj; 10 public: 11 virtual void print() { 12 cout << "mi = " << mi << ", " 13 << "mj = " << mj << endl; 14 } 15 }; 16 17 class Derived : public Demo { 18 int mk; 19 public: 20 Derived(int i, int j, int k) { 21 mi = i; 22 mj = j; 23 mk = k; 24 } 25 26 void print() { 27 cout << "mi = " << mi << ", " 28 << "mj = " << mj << ", " 29 << "mk = " << mk << endl; 30 } 31 }; 32 33 // 證實Derived內存排布與Test類同樣 34 struct Test { 35 void* p; 36 int mi; 37 int mj; 38 int mk; 39 }; 40 41 int main(int argc, const char* argv[]) { 42 cout << "sizeof(Demo) = " << sizeof(Demo) << endl; 43 cout << "sizeof(Derived) = " << sizeof(Derived) << endl; 44 45 Derived d(1, 2, 3); 46 Test* p = reinterpret_cast<Test*>(&d); 47 48 cout << "Before changing ..." << endl; 49 50 d.print(); 51 52 p->mi = 10; 53 p->mj = 20; 54 p->mk = 30; 55 56 cout << "After changing ..." << endl; 57 58 d.print(); 59 60 return 0; 61 }
C++多態的實現原理:spa
• 當類中聲明虛函數時,編譯器會在類中生成一個虛函數表指針
• 虛函數表是一個存儲成員函數地址的數據結構code
• 虛函數表是由編譯器自動生成與維護的對象
• virtual成員函數會被編譯器放入虛函數表中blog
• 存在虛函數表時,每一個對象中都有一個指向虛函數表的指針繼承
void run(Demo* p, int v) { p->add(v); }
編譯器確認add()是否爲虛函數?內存