我有一个Component
类,这是父类,例如 Sprite
类(class)。 Sprite
还有各种动画子项,但这不是这个问题的重点。我还有一个组件管理器,其中包含 map<string, Component>
。我将创建的每个组件存储在此映射中。目前有 12 种组件,但数量还会增加。
我的Component
类(class)有virtual void draw()
和update()
功能,与 Sprite
相同在这种情况下。然而,当我循环遍历组件映射时,它只调用 Component
draw()
和update()
.
我还没有真正找到对我真正有用的答案。
最佳答案
您正在经历object slicing —自从你的map
仅商店Component
按值的对象,这些对象不包含 Component
提供的任何信息子类。一般来说,子类型多态性只能通过指针类型起作用,而不能通过值类型起作用。所以需要通过指针来存储实例,最好是std::map<std::string, std::unique_ptr<Component>>
:
components["example"] = std::unique_ptr<Component>(new Example());
如果您使用的是非 C++11 编译器,请使用 std::map<std::string, Component*>
:
components["example"] = new Example();
并确保您delete
Component
清理期间的对象,例如在组件管理器的析构函数中。 C++03:
for (std::map<std::string, Component*>::const_iterator i = components.begin();
i != components.end(); ++i)
delete i->second;
C++11:
for (const auto& i : components)
delete i.second;
关于c++ - 全部继承自同一类的对象映射,调用对象方法而不是父类;由 小码哥发布于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11748661/