天天看點

多态

#include <iostream>

#include <string>

using namespace std;

class Parent

{

public:

virtual void print()

cout << "I'm Parent." << endl;

}

};

class Child : public Parent

void print()

 cout << "I'm Child." << endl;

void how_to_print(Parent* p)

 p->print(); // 展現多态的行為

int main()

 Parent p;

 Child c;

 how_to_print(&p); // Expected to print: I'm Parent.

 how_to_print(&c); // Expected to print: I'm Child.

 return 0;

ps:有一個父類和一個子類,他們各自有一個print函數(函數重寫),如果發生了對象指派(父類引用子類或者父類指針指向子類),然後調用對象的print函數,編譯器為了安全直接調用的是父類的print函數,但是有時候我們需要的是調用子類的print函數。這就是多态,調用同一個函數可能調用的是父類的也可能是子類的。

為了解決這個問題,給父類的print函數加上virtual ,這樣調用實際對象的print函數,編譯器判斷是父類對象還是子類對象,再調用實際的print函數。

函數重寫必須實作多态才有意義

ps:程式如何知道調用自己的或者是父類的函數呢?

當有繼承和virtual函數時,每個類會有一個虛函數表,裡面記錄了所有函數的位址。

如class A;class B:A;

對于B來說它的虛函數表裡首先會記錄A的函數位址,如果某個函數是多态virtual的,那麼會把這個函數的位址由A變為B,是以當調用這個函數的時候,實際上調用的是B的函數位址;當B有新的函數定義時,會在這個虛函數表裡追加新的函數位址。

長風破浪會有時,直挂雲帆濟滄海!