gpt4 book ai didi

c++ - 使用派生类的 vector 映射来调用其类的函数

转载 作者:行者123 更新时间:2023-11-30 01:43:58 25 4
gpt4 key购买 nike

假设我有这段代码:

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"]);

应该可以。

关于c++ - 使用派生类的 vector 映射来调用其类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36974498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com