从基类C++调用虚拟方法

Calling virtual method from base class C++

本文关键字:虚拟 方法 调用 C++ 基类      更新时间:2023-10-16

我是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,并且我需要在不知道它是派生类的情况下调用render/tick方法。。。我已经尝试过上面的代码,但我在提取的GEntity上调用render或tick方法的行中遇到了访问冲突
。。。我想要实现的是可能的吗
(很抱歉我的英语不太好,但我是意大利人)

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