C++映射唯一类并从值中提取子类
新 C++ 程序员来了。
我有以下地图定义:
typedef std::map<std::string, Option> MapType;
MapType my_map
选项是我创建的唯一类。我实际上从未将 Option 类本身添加到我的地图中。相反,我总是添加一个继承自 Option 的类,例如我有一个名为 IntOption 的类,它存储一个 int 变量(它的全部作用)。
现在,我可以通过执行以下操作将 IntOption 添加到我的地图中:
IntOption add;
my_map.insert(std::pair<string, IntOption>("a key here", add));
这工作正常,因为当我执行 a 时,
my_map["a key here"]
它将返回值“add”。
现在我向你们所有好人提出的问题是如何从返回值中获取子类变量?我可以执行以下操作
my_map["a key here"].getVariableA(); // this is in the base class Option.
,但不能执行
my_map["a key here"].getIntVariable(); //this fails because it doesnt recognize the
// getter,因为它不在基类中,而是在扩展选项的类中。
我该如何解决这个问题?
我考虑过 typedef std::map MapType;
我不知道如何进行动态转换,也不知道如何将指向类的指针添加到地图中。
New C++ programmer here.
I have the following map definition:
typedef std::map<std::string, Option> MapType;
MapType my_map
Option is a unique class i created. I never actually add the Option class into my map by itself. Instead I am always adding a class that inherits from Option, for example i have a class called IntOption that store an int variable (its all it does) .
Now i have no problem adding IntOption into my map by doing:
IntOption add;
my_map.insert(std::pair<string, IntOption>("a key here", add));
This works fine because when i do a
my_map["a key here"]
it will return the value "add".
Now my question to you all good people is how can i get the subclass variable out of the return value? I can do the following
my_map["a key here"].getVariableA(); // this is in the base class Option.
but i cannot do
my_map["a key here"].getIntVariable(); //this fails because it doesnt recognize the
// getter because it is NOT in the base class but the class extending Option.
How do i fix this problem?
I have considered
typedef std::map MapType;
buy i cannot figure out how to do the dynamic casting nor how to add the pointer to the class into the map.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不会按照您设置的方式工作。该映射假设它只保存 Option 的实例,因此它将丢弃您尝试发送给它的任何 IntOption 数据。您将不得不依靠指向选项的指针。
请注意,您现在必须处理内存管理,并决定何时释放您的选项。 std::auto_ptr 可能会对此有所帮助。
It won't work the way you have it set up. The map is assuming that it only holds instances of Option, so it will be throwing away any IntOption data you try to send it. You will have to fall back on pointers to the options.
Note that you'll have to handle memory management now, and decide when your options will be deallocated. std::auto_ptr might help with that.