广州网站建设丿新科送推广,专业制作网站推荐,山东建设发展研究院网站,官方网站找工作公众号虚函数的作用就是当一个类继承另一个类时#xff0c;两个类有同名函数#xff0c;当你使用指针调用时你希望使用子类的函数而不是父类的函数#xff0c;那么请使用 virutal 和 override 关键词
看代码#xff1a;
#include iostream
#include string
#in…虚函数的作用就是当一个类继承另一个类时两个类有同名函数当你使用指针调用时你希望使用子类的函数而不是父类的函数那么请使用 virutal 和 override 关键词
看代码
#include iostream
#include string
#include vector
#include algorithm /* sort*/
#include functional /*std::greaterint()*/
#include game.hclass 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();
}