在 C++ 中,vector 类存储一个对象数组。在这种情况下,我存储指向派生类对象(Dogs)的指针。在某些时候,我想将此向量视为指向基类(动物)对象的指针。这是“正确”/无争议的方式,对吗?为什么我不能这样做?
#include <vector>
using namespace std;
class Animal { };
class Dog : public Animal { };
int main(int argc, char *argv[]) {
vector<Dog*> dogs;
dogs.push_back(new Dog());
dogs.push_back(new Dog());
vector<Animal*> animals = dogs; // This doesn't seem to work.
// This is really what I want to do...
vector<Animal*> all_animals[] = {dogs, cats, birds};
}
错误:
Untitled.cpp:11:18: error: no viable conversion from 'vector<class Dog *>' to 'vector<class Animal *>'
vector<Animal*> animals = dogs;
^ ~~~~
/usr/include/c++/4.2.1/bits/stl_vector.h:231:7: note: candidate constructor not viable: no known conversion from 'vector<Dog *>' to 'const std::vector<Animal *, std::allocator<Animal *> > &' for 1st argument
vector(const vector& __x)
^