在map(c ++,STL)方面需要帮助

Mik*_*ley 3 c++ polymorphism stl map

其实我是C++的新手.我尝试了一些东西(实际上是地图容器),但是它没有按照我想象的方式工作......在发布我的代码之前,我会很快解释它.

我创建了3个类:

ClassA ClassDerivedA ClassAnotherDerivedA

最后两个来自"ClassA".

我进一步创建了一张地图:

  map<string,ClassA> test_map;
Run Code Online (Sandbox Code Playgroud)

我将一些对象(来自Type 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Fre*_*son 13

问题是切片.您正在ClassA地图中存储值.将派生类实例存储到地图中时,会将切片切换为ClassA对象.您需要在地图中存储指针而不是值.

有关切片的更多信息,请参阅此内容:什么是对象切片?