从基类C ++调用虚方法

时间:2012-11-22 18:57:29

标签: c++ function virtual

我是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);
    //...
};

Player.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的arraylist(我创建的结构),然后,当我得到它时,我得到它作为一个GEntity,我需要调用render / tick方法而不知道它的派生类... 我已尝试使用上面的代码,但是我在提取的GEntity上调用了render或tick方法的行中出现了访问冲突...
...是我想要的甚至可能实现的目标?
(对不起,如果我的英语不太好,但我是意大利语)

1 个答案:

答案 0 :(得分:3)

如果你有一个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()

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

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

// some c++11
for ( auto e : entities) {
  e->render();
}
相关问题