使用派生类的向量映射调用其类的函数

Using a map of vectors of a derived class to call the its class's function

本文关键字:调用 函数 映射 向量 派生      更新时间:2023-10-16

假设我有这样的代码:

class Parent{
public:
   virtual void printm(){
     cout << "Parent" << endl;
}
class Child:public Parent{
public:
   void printm(){
     cout << "Child" << endl;
}
int main()
{
Parent * aPerson = new Child;
map<string, vector<Parent*>> family;
family["Test"].pushback(aPerson);
//I want to be able to do SOMETHING like this but I'm wondering if that's  
//possible? I know it looks crazy but please bear with me
printdata(family["Test"]);
}
void printdata(Parent * x){
x->printm();
}

我到处找都找不到和我有类似问题的人。我觉得这是可能的。我知道这样做要简单得多:

printdata(aPerson);

但是。。再一次我只想知道所有的可能性。

family["Test"]的计算结果为std::vector<Parent*>。您可以添加一个函数重载:

void printdata(std::vector<Parent*> const& x)
{
   for(auto item : x )
   {
      printdata(item);
   }
}

然后,

printdata(family["Test"]);

应该起作用。