Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

pointers - C++ Polymorphism and Vectors, pointing a derived class of vectors to a base class of vectors

Say: Apple is derived from a base Fruit Class, then there is a class ApplePicker derived from a base FruitPicker class.
The ApplePicker class has vector<Apple> appleList, the Fruit picker class has a pointer to a vector<Fruit> i.e. vector<fruit>* fruitList.

I need to be able to set the vector to this pointer, so abstract methods can be run in the fruit picker class(as they only are concerned with the fruit members). But I am having trouble setting this, when I tried to do this:

this->fruitList = &(this->AppleList);

It gives me the error cannot convert to vector<Apple> to vector<Fruit>. I tried static cast and it gave me the same error. I did a similar thing to a non-vector base class and derived class and it was fine.

I am new to C++, and I am using it on Android via NDK.

So is what I am trying to do impossible and I have to use a vector of pointers like vector<Fruit*>.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Think about it: if vector<Apple> could substitute vector<Fruit> (in other words, if the conversion you are expecting to occur was actually legal), then you could provide a vector<Apple> in input to a function that expects a vector<Fruit>.

A function that expects a vector<Fruit> may well add a Banana to that vector, because Banana is a Fruit (neglecting for the moment the fact that you would get slicing if your vector stores objects of type Fruit rather than pointers to such objects, but that's kind of a different story). If you were passing a vector<Apple> to that function, you would break the invariant of vector<Apple> (i.e., the fact that it can contain only apples).

Inheritance in OOP works for those cases where one type is able to universally substitute another type, and the fact that A can substitute B does not mean that V<A> can substitute V<B>.

If you need to write a generic routine that works with both kinds of vectors, use templates to achieve compile-time genericity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...