其实我是C++新手。我尝试了一些东西(实际上是地图容器),但它不会像我认为的那样工作......在发布我的代码之前,我会尽快解释它。需要帮助地图(C++,STL)
我创建了3类:
ClassA的 ClassDerivedA ClassAnotherDerivedA
最后两个那些从 “ClassA的” 导出。
此外我创建的地图:
map<string,ClassA> test_map;
我把一些对象(从类型ClassDerivedA和ClassAnotherDerivedA)到地图。请记住:映射值来自类型“ClassA”。这只会因为多态性而起作用。最后,我创建了一个遍历我的地图的迭代器,并将用户输入与我在地图中的键进行比较。如果它们匹配,它将调用一个名为“printOutput”的特定方法。
并且存在问题: 尽管我将“printOutput”声明为“虚拟”,但唯一调用的方法是来自我的基类的,但为什么? 这里是代码:
#include <iostream>
#include <map>
using namespace std;
class ClassA
{
public:
virtual void printOutput() { cout << "ClassA" << endl; }
};
class ClassDerivedA : public ClassA
{
public:
void printOutput() { cout << "ClassDerivedA" << endl; }
};
class ClassAnotherDerivedA: public ClassA
{
public:
void printOutput() { cout << "ClassAnotherDerivedA" << endl; }
};
int main()
{
ClassDerivedA class_derived_a;
ClassAnotherDerivedA class_another_a;
map<string,ClassA> test_map;
test_map.insert(pair<string,ClassA>("deriveda", class_derived_a));
test_map.insert(pair<string,ClassA>("anothera", class_another_a));
string s;
while(cin >> s)
{
if(s != "quit")
{
map<string,ClassA>::iterator it = test_map.find(s);
if(it != test_map.end())
it->second.printOutput();
}
else
break;
}
}
作为一个侧面说明,您可以使用make_pair(),而不是对<字符串,ClassA的>(),少写... – 2010-05-13 21:43:54