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

2022-01-24 00:00:00 pointers polymorphism vector c++

说:苹果派生自一个基础水果类,然后有一个类 ApplePicker 派生自一个基础 FruitPicker 类.
ApplePicker 类具有 vector<Apple>appleList,水果选择器类有一个指向 vector 的指针,即 vector*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>到向量<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 可以替代 vector (换句话说,如果您期望发生的转换实际上是合法的),那么您可以在输入中提供一个 vector 到一个需要 vector 的函数.

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 的函数很可能会向该向量添加 Banana,因为 BananaFruit (暂时忽略这样一个事实,即如果您的向量存储类型为 Fruit 的对象而不是指向此类对象的指针,您将获得 slicing 的事实,但这是一种不同的故事).如果您将 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.

相关文章