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

允我心安 提交于 2019-12-20 02:15:12

问题


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*>.


回答1:


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.



来源:https://stackoverflow.com/questions/15849639/c-polymorphism-and-vectors-pointing-a-derived-class-of-vectors-to-a-base-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!