从基类C++调用虚拟方法
Calling virtual method from base class C++
我是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();
}
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 使用模板而不是虚拟方法的管道模式
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 为什么调用没有正文的纯虚拟方法不会导致链接器错误?
- 出于什么目的,非虚拟方法将与C++一起使用?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 如何重写继承的嵌套类中存在的虚拟方法
- 私有虚拟方法有什么用?
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 确保模拟的 GTest 方法覆盖虚拟方法
- CPP 继承虚拟方法解析顺序
- 我是否应该在包含虚拟方法的类上使用'memcpy'?如果没有,如何替换它?
- 用c++中的纯虚拟方法抽象模板类
- 解决虚拟方法的歧义继承的两种方法
- 没有针对完全专用模板类的外联虚拟方法定义