简体   繁体   中英

C++ storing derived objects within a map

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

You can use dynamic_cast to cast back to the derived class, if you knwo what class it is.

dynamic_cast<DerivedItem*>(itemmap[vnum])->derivedFunction();

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:

itemmap<DerivedItem>[vnum]->derivedFunction()

You won't be able to access members specific to the DerivedItem class with an Item pointer. You could cast it:

val = static_cast<DerivedItem*>(itemmap[vnum])->d;

....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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM