C ++多态和向量,将向量的派生类指向向量的基类

问题描述:

说: 苹果派生自基本Fruit Class,然后有一个派生类ApplePicker来自基本FruitPicker类.
ApplePicker类具有vector<Apple> appleList,Fruit picker类具有指向vector<Fruit>的指针,即vector<fruit>* fruitList.

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

它给我错误cannot convert to vector<Apple> to vector<Fruit>.我尝试了静态转换,它给了我同样的错误.我对非向量基类和派生类做了类似的事情,这很好.

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.

我是C ++的新手,我正在通过NDK在Android上使用它.

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

我试图做的事情也是不可能的,我必须使用像vector<Fruit*>这样的指针向量.

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

考虑一下:如果vector<Apple>可以替代vector<Fruit>(换句话说,如果您期望进行的转换实际上是合法的),那么您可以在期望vector<Fruit>的函数的输入中提供vector<Apple>.

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

期望vector<Fruit>的函数可能会在该向量上添加Banana,因为BananaFruit(暂时忽略了得到 slicing 的事实如果您的向量存储的是类型为Fruit的对象,而不是指向此类对象的指针,但这有点不同.如果将vector<Apple>传递给该函数,则会破坏vector<Apple>的不变式(即,它只能包含苹果的事实).

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

OOP中的继承适用于一种类型可以通用替换另一种类型的情况,并且A可以替换B的事实并不意味着V<A>可以替换V<B>.

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.