【发布时间】:2013-10-05 21:19:11
【问题描述】:
我对 C++ 比较陌生,并且来自 C# 背景,我在这个列表迭代中遇到了问题:
我有一个方法循环遍历对象列表并为每个对象调用一个更新方法,效果很好。该列表的类型为std::list<EngineComponent>,称为engineComponents。
void Game::Update()
{
for (EngineComponent component: this->engineComponents)
{
component.Update();
}
}
我还有一个EngineComponent 的子类,称为DrawableEngineComponent。
当我尝试进行类似的迭代时出现问题:
void Game::Draw()
{
for (DrawableEngineComponent component: this->engineComponents)
{
component.Draw();
}
}
这会产生错误“不存在从 'EngineComponent' 到 'DrawableEngineComponent' 的合适的用户定义转换”。鉴于这个实现在 C# 中一切都很好而且很花哨,我不确定如何最好地在 C++ 中解决这个问题。
我可以想到一些可以/应该工作的替代方法,但我想知道 C++ 中是否有功能以类似于 C# 的方式执行此操作,而无需手动定义转换。
这两个类的定义如下:
class EngineComponent
{
public:
EngineComponent(void);
~EngineComponent(void);
virtual void Update(void);
};
class DrawableEngineComponent : public EngineComponent
{
public:
DrawableEngineComponent(void);
~DrawableEngineComponent(void);
virtual void Draw(void);
};
是的,我稍微复制了 XNA 框架;)
【问题讨论】:
-
该演员尝试指出了一个潜在的切片问题,您最好通过read this question and answers 了解更多信息。
-
您说这在 C# 中有效,但我不确定这是不是真的 :-) 在 C# 中,如果列表中的组件之一是 not 可绘制的,会发生什么情况。它会崩溃吗?或者跳过列表中的那个项目?请说明您在这方面的期望/期望行为。
-
@AaronMcDaid 你是对的,它没有。写这个的时候有点迷茫。在 C# 中很容易做到,只需检查循环中出现的每个对象(使用一行代码),这是我应该写的。好地方:)
标签: c++ inheritance subclassing stdlist