在map(c,STL)方面需要帮助
发布时间:2020-12-16 10:50:22 所属栏目:百科 来源:网络整理
导读:其实我是C的新手.我尝试了一些东西(实际上是地图容器),但是它没有按照我想象的方式工作……在发布我的代码之前,我会很快解释它. 我创建了3个类: ClassA的 ??ClassDerivedA ??ClassAnotherDerivedA 最后两个来自“ClassA”. 我进一步创建了一张地图: mapstr
其实我是C的新手.我尝试了一些东西(实际上是地图容器),但是它没有按照我想象的方式工作……在发布我的代码之前,我会很快解释它.
我创建了3个类: ClassA的 最后两个来自“ClassA”. 我进一步创建了一张地图: map<string,ClassA> test_map; 我将一些对象(来自Type ClassDerivedA和ClassAnotherDerivedA)放入地图中.请记住:映射值来自“ClassA”类型.这只会因多态性而起作用.最后,我创建了一个迭代器,它在我的地图上运行,并将用户输入与地图中的键进行比较.如果它们匹配,它将调用一个名为“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; } } 解决方法
问题是切片.您正在地图中存储ClassA值.将派生类实例存储到地图中时,会将切片切换为ClassA对象.您需要在地图中存储指针而不是值.
有关切片的更多信息,请参阅此内容:What is object slicing? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |