虚函数的作用就是当一个类继承另一个类时,两个类有同名函数,当你使用指针调用时你希望使用子类的函数而不是父类的函数,那么请使用 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();
}