为什么不调用虚函数? [英] Why is virtual function not being called?
本文介绍了为什么不调用虚函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
//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); }
我在我的gameworld类中有一个向量。当我添加一个guitext实体到这个向量,我希望它调用guitext :: draw()函数。但是基类函数正在被调用。
I have a vector in my gameworld class. When I add push a guitext entity to this vector I expect it to call the guitext::draw() function. But the base class function is being called. What am I doing wrong?
推荐答案
你创建了一个 entity
。这些对象始终有实体
。如果你想调用多态性,它们需要是指针或引用。 实体
的向量如何存储 guitext
?没有足够的空间,它不知道如何销毁它,等等。
You made a vector of entity
. Those objects always have type entity
. If you want to invoke polymorphism, they need to be pointers or references. How can a vector of entity
store a guitext
? There's not enough space, it doesn't know how to destroy it, etc etc.
这篇关于为什么不调用虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文