//GUITEXT
class guitext : public entity {
public:
guitext(graphics *gfx, std::string _text, float _x, float _y,
float _size, float timeToLive);
bool update(float deltaTime, gameworld *world);
void draw(graphics *gfx);
};
void guitext::draw(graphics *gfx) { printf("draw"); }
//ENTITY
class entity {
public:
virtual bool update(float deltaTime, gameworld *world)
{ return false; }
virtual void draw(graphics *gfx) { }
};
//GAMEWORLD
void gameworld::addEntity(entity e) { entitys.push_back(e); }
//MAIN
for(int i = 0; i < (int)entitys.size(); i++) { entitys[i].draw(gfx); }
我的游戏世界类中有一个 vector 。当我将一个 guitext 实体添加到此 vector 时,我希望它调用 guitext::draw() 函数。但是正在调用基类函数。我做错了什么?
最佳答案
你制作了一个实体
的 vector 。这些对象始终 具有entity
类型。如果要调用多态性,它们需要是指针或引用。 entity
vector 如何存储 guitext
?没有足够的空间,它不知道如何销毁它,等等。
关于c++ - 为什么不调用虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4585356/