【问题标题】:Calling virtual method from base class C++从基类 C++ 调用虚方法
【发布时间】:2012-11-22 18:57:28
【问题描述】:

我是 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 的数组列表(我创建的结构)中,然后,当我取回它时,我将它作为 GEntity 获取,并且我需要在不知道它的派生类的情况下调用渲染/滴答方法... 我已尝试使用上面的代码,但在提取的 GEntity 上调用渲染或刻度方法的行中出现访问冲突...
...是我想要实现的目标吗?
(对不起,如果我的英语不太好,但我是意大利人)

【问题讨论】:

  • 问题可能存在于您的arraylist。它是否包含指向GEntity 的指针或GEntity 的实际实例?
  • 数组/结构声明呢?这才是关键。
  • 它包含实际实例
  • 您正在体验object slicing
  • 您需要的是指针,而不是实例。使用智能指针作为偏好。

标签: c++ function virtual


【解决方案1】:

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

【讨论】:

  • 你不应该写for (_auto_ e : entities)吗?
猜你喜欢
  • 1970-01-01
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2015-03-30
  • 2016-07-12
  • 2019-05-24
  • 1970-01-01
相关资源
最近更新 更多