3

我是 C++ 新手,我很难弄清楚我的虚函数出了什么问题。所以,这就是我所拥有的:

GEntity.h

class GEntity
{
public:
    //...
    virtual void tick(void);
    virtual void render(void);
    //...
};

GEntity.cpp

//...
void GEntity::tick(void){}
void GEntity::render(void){}
//...

GLiving.h

class GLiving : public GEntity
{
public:
    //...
    virtual void tick(void);
    virtual void render(void);
    //...
};

GLiving.cpp

//...
void GEntity::tick(void){}
void GEntity::render(void){}
//...

然后我有其他派生自 GLiving (Player, Enemy) 的类,它们实现了这两种方法的自己的版本: Player.h

class Player : public GLiving
{
public:
    //...
    void tick(void);
    void render(void);
    //...
};

播放器.cpp

//...
void GEntity::tick(void)
{
    //Here there's some actual code that updates the player
}
void GEntity::render(void)
{
    //Here there's some actual code that renders the player
}
//...

现在,如果我声明一个 Player 类的对象,并调用 render/tick 方法,一切都很顺利,但我处于将我的播放器添加到 GEntity 的数组列表(我创建的结构)的情况,然后,当我取回它时,我将它作为 GEntity 获取,并且我需要在不知道它的派生类的情况下调用渲染/滴答方法...我已经尝试使用上面的代码,但我在其中的行中遇到访问冲突我在提取的 GEntity 上调用 render 或 tick 方法...
...是我想要实现的吗?
(对不起,如果我的英语不太好,但我是意大利人)

4

1 回答 1

3

如果您有一个 then 数组,GEntity则每次“添加”派生类型时,都会发生等效情况:

GEntity g;
Player p;
g = p; // object slicing, you assigned a Player to a GEntity object.
g.render(); // GEntity::render() gets called

另一方面,您可以使用指向基类的指针来访问派生方法:

GEntity* g;
Player p;
g = &p;
g->render(); // calls Player::render()

因此,处理容器中的多态性的一种方法是拥有指向基类的(最好是智能的)指针的数组/容器。为简单起见,此示例使用原始指针,但您应该在实际代码中使用智能指针:

std::vector<CEntity*> entities;
entities.push_back(new Player);
entities.push_back(new GLiving);

// some c++11
for ( auto e : entities) {
  e->render();
}
于 2012-11-22T19:07:53.917 回答