gpt4 book ai didi

c++ - std::vector 和多态性

转载 作者:太空宇宙 更新时间:2023-11-03 10:20:27 25 4
gpt4 key购买 nike

#include <iostream>
#include <vector>

using namespace std;

class Base {
public:
virtual ~Base(){}
};

class Deriv : public Base {
public:
virtual ~Deriv(){}
};

void f(Base *){
cout << "f(Base *)" << endl;
}

void f(vector<Base *>){
cout << "f(vector<Base *>)" << endl;
}

int main(int argc, const char *argv[])
{
Deriv *d = new Deriv;
vector<Deriv *> v;
v.push_back(d);

f(d); // works
//f(v); // does not compile
return 0;
}

第一个 f() 有效,但第二个给出编译时错误:

f(vector<Deriv *>) not found.

我的问题:有没有办法让它工作:某种 vector 多态性?

最佳答案

您想要的属性称为协方差。答案是否定的,你不能这样做: vector 不是协变的。

为什么不允许这样做的典型例子是这样的:

class Deriv2 : public Base {
public:
virtual ~Deriv2(){}
};

void f(vector<Base *>& v){
v.push_back(new Deriv2); // oops, just pushed a Deriv2 into a vector of Deriv
}

如果您不向 vector 添加元素,您可以只传递一对输入 迭代器。传递输出迭代器也不起作用。

template <typename InputIterator>
void f(InputIterator first, InputIterator last);

f(v.begin(), v.end());

关于c++ - std::vector 和多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7399885/

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