虛函數的作用就是當一個類繼承另一個類時,兩個類有同名函數,當你使用指針調用時你希望使用子類的函數而不是父類的函數,那么請使用 virutal 和 override 關鍵詞
看代碼:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> /* sort*/
#include <functional> /*std::greater<int>()*/
#include "game.h"class Entity {/*解決辦法就是使用虛函數,同時使用標記覆蓋功能 */
public:virtual std::string GetName() { return "Entity"; }
};void PrintName(Entity* entity) { /*同樣的,我們這里希望傳入Player的GetName(),但并沒有*/std::cout << entity->GetName() << std::endl;
}class Player : public Entity {
private:std::string m_Name;
public:Player(const std::string& name): m_Name(name){}std::string GetName() override { return m_Name; } /* here! */
};int main() {Entity* e = new Entity();std::cout << e->GetName() << std::endl;Player* p = new Player("Che");std::cout << p->GetName() << std::endl;Entity* entity = p;std::cout << entity->GetName() << std::endl; /*這里你可能想要打印的是Player的名字,但是你會得到Entity*/PrintName(entity);/*同樣的,得到了Entity,但是你希望得到Che*/std::cin.get();
}