问题描述
在c ++中使用std :: map时,是否可以将继承的类存储为地图中的基类,并仍然能够调用它们的重载方法?请参阅此示例:
When using std::map in c++, is it possible to store inherited classes as their "base class" in the map and still being able to call their overloaded methods? See this example:
#include <iostream>
#include <map>
class Base
{
public:
virtual void Foo() { std::cout << "1"; }
};
class Child : public Base
{
public:
void Foo() { std::cout << "2"; }
};
int main (int argc, char * const argv[])
{
std::map<std:string, Base> Storage;
Storage["rawr"]=Child();
Storage["rawr"].Foo();
return 0;
}
以下代码写为1。当你使用std :: map时,不知何故告诉我多态性不起作用。
This following code writes "1". Which somehow tells me that polymorphism doesn't work when you use std::map.
推荐答案
case因为std :: map将Base存储为值类型,因此。
Polymorphism doesn't work in that case because the std::map stores the Base as a value type, so the objects get sliced.
如果你想在存储对象上有多态性,你需要存储指针或使用来实现相同的功能。这意味着你需要记住删除内存后(请不要把指针堆栈对象到地图)
If you want to have polymorphism on stored objects, you need to store pointers or use one of the boost ptr containers to effect the same. This means you need to remember to delete the memory afterwards (please don't put pointers to stack objects into the map)
这篇关于std :: map无法处理多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!