C++在映射中存储派生对象
是的,我对 c++ 还很陌生,所以我还在这儿学习。如果我以错误的方式解决这个问题,请告诉我,但如果可能的话,请尝试为我指出正确的方向(也许带有教程的链接)。
我一直在使用 std::map 并用它来存储对象(项目)。这很好用。问题是尝试在地图中存储派生项目。我已经让它工作了,但它似乎正在分割派生对象。
所以说 item 具有属性 a、b 和 c。食物源自具有额外属性 d 和 e 的 item。当 d 和 e 存储在项目地图中时,我无法访问它。编译器说:
“错误:‘class item’没有名为‘d’的成员”
是否可以使用 std::map 多态,或者我是否需要使用另一个库(如 boost)? Boost 看起来相当复杂,我希望在我还在学习的时候有一种方法可以用 map 来实现它。这是我正在使用的一些代码,以使其更清楚我的意思。
项目地图声明如下:
typedef std::map <int, tItem*> itemMap;
事物像这样添加到其中:
Item * item = new Item (a, b, c);
itemmap [vnum] = item;
DerivedItem * deriveditem = new DerivedItem (a, b, c, d, e);
itemmap [vnum] = deriveditem;
这有效,但我无法访问派生项目的 d 和 e。
感谢大家的帮助
Right, I am fairly new to c++ so I am still learning here. If I am going about this in the wrong way then tell me, but try to point me in the right direction if possible (perhpaps with a link to a tutorial).
I have being playing around with std::map and have used it to store an object (item). This works fine. The problem is trying to store derived items within the map. I have got it working but it seems to be slicing up the derived object.
So say item has the attributes a,b and c. and food is derived from item with the extra attributes d and e. I cannot access d and e when it is stored in a map of items. The compiler says:
"error: ‘class item’ has no member named ‘d’"
Is it possible to use std::map polymorphicaly or do I need to use another library like boost? Boost seems rather complex and I was hoping that there was a way to do it with map while I am still learning. Here is some of the code that I am playing with to make it clearer what I mean.
Map of items is declared as so:
typedef std::map <int, tItem*> itemMap;
Things are added to it like this:
Item * item = new Item (a, b, c);
itemmap [vnum] = item;
DerivedItem * deriveditem = new DerivedItem (a, b, c, d, e);
itemmap [vnum] = deriveditem;
This works, but I cannot access d and e of the derived item.
Thanks for the help guys
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您知道派生类是什么,则可以使用
dynamic_cast
强制转换回派生类。http://en.wikipedia.org/wiki/Dynamic_cast
如果您希望自动完成此操作,您可以从 std::map 派生一个新的模板类,其中
[]
运算符具有模板参数。但在这种情况下,您必须在获取项目时传递类型:You can use
dynamic_cast
to cast back to the derived class, if you knwo what class it is.http://en.wikipedia.org/wiki/Dynamic_cast
If you want this to be done automatically, you can derive a new template class from std::map, where the
[]
operator has a template argument. But in this case you have to pass the type when you get the item:您将无法使用
Item
指针访问特定于DerivedItem
类的成员。您可以投射它:....但这取决于知道哪些项目是地图中的哪种类型。
对于多态行为,通常您会在派生类中重写父类中的一个方法,该方法的行为不同。
You won't be able to access members specific to the
DerivedItem
class with anItem
pointer. You could cast it:....but that depends on knowing which items are which type in the map.
For polymorphic behaviour, usually you would have a method in the parent class overridden in the derived classes that behaves differently.