c++ - 为什么不调用虚函数?

标签 c++

//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/

相关文章:

c++ - gdb 启动但不逐行执行

模板函数 <queue> 中的 C++ 内存错误

c++ - 我应该在正文还是 header 中定义 C++ 空函数?

c++ - 在值类型列表中保存引用类型?

c++ - 为什么在初始化列表中初始化 POD 数据时必须进行 C 风格的类型转换?

c++ - 如何修复此左值警告?

c++ - 为什么 C++ 有一个引用类型 "&"?

c++ - 根据对象类型切换

c++ - 类中没有使用const静态变量优化掉?

c# - 我将如何制作一个程序来通过远程连接监控另一个系统的生命体征?