Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

c++ - Trying to assign vector of Base* from vector of Derived*

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;
}

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 works because that method just takes a T const& (or T&&), so anything convertible to a Base* will be acceptable - which a Derived* is.

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...