【发布时间】: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。
-
您需要的是指针,而不是实例。使用智能指针作为偏好。