我是比较新的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框架位;)
这种投射尝试尖叫出潜在的切片问题,你可能会做得很好[阅读这个问题和答案](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c/274634#274634)了解更多关于它 – WhozCraig
你说这个在C#中有效,但我不确定这是真的:-)在C#中,如果列表中的某个组件是* not * Drawable,会发生什么情况。它会崩溃吗?或者跳过列表中的项目?请澄清你在这方面的期望/愿望。 –
@AaronMcDaid你是对的,它没有。当我写这个时,我有点困惑。在C#中通过检查每个对象在循环中出现时(使用一行代码)很容易实现,这是我应该写的。好地方:) –