尝试从Derived *的向量分配Base *的向量 [英] Trying to assign vector of Base* from vector of Derived*

查看:63
本文介绍了尝试从Derived *的向量分配Base *的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个非常基本的问题,但我无法弄清楚.我有一个std::vector指向派生对象的原始指针,我只想使用赋值运算符将其复制到Base指针的另一个向量.使用VC ++,我会收到错误C2679二进制'=':找不到运算符..."顺便说一句,我不需要对象的深层副本,我只想复制指针.示例代码:

This seems like a pretty basic problem, but I can't figure it out. I have a std::vector of raw pointers to Derived objects, and I just want to copy it to another vector of Base pointers using the assignment operator. With VC++ I get error C2679 "binary '=': no operator found..." BTW I don't want a deep copy of the objects, I just want to copy the pointers. Sample code:

#include <vector>
using namespace std;

struct Base{};    
struct Derived: public Base {};

int main (int argc, char* argv[])
{
    vector<Derived*> V1;
    vector<Base*> V2;
    V2 = V1;  //Compiler error here
    return 0;
}

让我感到困惑的是,我可以通过遍历并使用push_back来复制矢量,如下所示:

What confuses me is that I can copy the vector by looping through it and using push_back, like this:

for (Derived* p_derived : V1)
    V2.push_back(p_derived);

所以我的问题是,为什么push_back起作用却分配失败?对我来说似乎是同一件事.

So my question is why does the assignment fail, while push_back works? Seems like the same thing to me.

推荐答案

这是因为虽然BaseDerived有关系,但vector<Base*>vector<Derived*>之间没有关系.就类层次结构而言,它们是完全不相关的,因此您不能将一个分配给另一个.

That's because while Base and Derived have a relationship, there is no relationship between vector<Base*> and vector<Derived*>. As far as class hierarchy is concerned, they are entirely unrelated, so you can't assign one to the other.

您正在寻找的概念称为 协方差 .例如,在Java中,String[]Object[]的子类型.但是在C ++中,这两种类型只是不同的类型,与String[]Bar没有更多的关系.

The concept you are looking for is called covariance. In Java for instance, String[] is a subtype of Object[]. But in C++, these two types are just different types and are no more related than String[] and Bar.

push_back之所以起作用,是因为该方法只需要一个T const&(或T&&),因此任何可转换为Base*的东西都是可以接受的-Derived*就是这样.

push_back works because that method just takes a T const& (or T&&), so anything convertible to a Base* will be acceptable - which a Derived* is.

也就是说,vector有一个带有一对迭代器的构造函数,在这里应该更容易使用:

That said, vector has a constructor that takes a pair of iterators, which should be easier to use here:

vector<Base*> v2(v1.begin(), v1.end());

或者,因为它已经被构造:

Or, since it is already constructed:

v2.assign(v1.begin(), v1.end());

这篇关于尝试从Derived *的向量分配Base *的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆