我想要一个派生类指针的向量作为基类指针 [英] I want a vector of derived class pointers as base class pointers

查看:146
本文介绍了我想要一个派生类指针的向量作为基类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,vector类存储一个对象数组。在这种情况下,我存储指向派生类对象(Dogs)的指针。在某些时候,我想将此向量视为指向基类(动物)对象的指针。这是正确/无争议的方式吗?为什么我不能这样做?

In C++, the vector class stores an array of objects. In this case, I am storing pointers to derived class objects (Dogs). At some point, I want to treat this vector as pointers to objects of the base class (Animals). This is the "right"/non controversial way right? Why can't I do this?

#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)
  ^


推荐答案

std :: vector 有一个复制构造函数,但它要求您复制完全相同类型的向量。幸运的是,还有另一个构造函数,它接受一对迭代器并添加范围内的所有元素,因此您可以这样做:

There is a copy constructor for a std::vector but it requires you to copy the exact same type of vector. Fortunately, there is another constructor which takes a pair of iterators and adds all the elements in the range, so you can do this:

vector<Animal*> animals(dogs.begin(),dogs.end());

这会创建一个 Animal 指针的新向量通过迭代每个 Dog 指针。每个 Dog 指针都会转换为 Animal 指针。

This creates a new vector of Animal pointers by iterating through each Dog pointer. Each Dog pointer is converted to an Animal pointer as it goes.

这是一个更完整的例子(使用C ++ 11):

Here is a more complete example (using C++11):

#include <vector>

struct Animal { };

struct Dog : Animal { };

struct Cat : Animal { };

struct Bird : Animal { };

int main(int,char**)
{
  Dog dog1, dog2;
  Cat cat1, cat2;
  Bird bird1, bird2;
  std::vector<Dog *> dogs = {&dog1,&dog2};
  std::vector<Cat *> cats = {&cat1,&cat2};
  std::vector<Bird *> birds = {&bird1,&bird2};
  std::vector<std::vector<Animal *>> all_animals = {
    {dogs.begin(),dogs.end()},
    {cats.begin(),cats.end()},
    {birds.begin(),birds.end()}
  };
}

这篇关于我想要一个派生类指针的向量作为基类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆