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());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…