我想要一个派生类指针的向量作为基类指针

时间:2013-08-14 04:08:08

标签: c++ inheritance

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

4 个答案:

答案 0 :(得分:12)

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

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

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

这是一个更完整的例子(使用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()}
  };
}

答案 1 :(得分:1)

可接受的解决方案很好,但是有一个很大的缺点:它维护有问题的向量内容的副本。每当向量之一更新时,我们也需要更新冗余数据以保持全局状态一致。不太喜欢,决定尝试解决这个问题(很遗憾,需要发现这需要做很多工作...):

class AllAnimals
{
    struct Wrapper
    {
        virtual ~Wrapper() { }
        virtual Animal* begin() = 0;
        virtual Animal* end() = 0;
    };

    template <typename T>
    struct SpecificWrapper : Wrapper
    {
        T& animals;
        SpecificWrapper(T& animals)
                : animals(animals)
        { }
        Animal* begin() override
        {
            return *animals.begin();
        }
        Animal* end() override
        {
            return *animals.end();
        }
    };

    std::vector<std::unique_ptr<Wrapper>> wrappers;

public:
    class iterator : public std::iterator<std::forward_iterator_tag, Animal*>
    {
        friend class AllAnimals;
        decltype(wrappers)::iterator current, end;
        Animal* animal;
        iterator(decltype(current) begin, decltype(end) end)
                : current(begin), end(end)//, animal(nullptr)
        {
            while(current != end && (*current)->begin() == (*current)->end())
            {
                ++current;
            }
            animal = current == end ? nullptr : (*current)->begin();
        }
    public:
        bool operator==(iterator const& other)
        {
            return current == other.current && animal == other.animal;
        }
        bool operator!=(iterator const& other)
        {
            return !(*this == other);
        }
        iterator& operator++()
        {
            if(++animal == (*current)->end())
            {
                ++current;
                animal = current == end ? nullptr : (*current)->begin();
            }
            return *this;
        }
        iterator operator++(int)
        {
            iterator i(*this);
            ++*this;
            return i;
        }
        Animal* operator*()
        {
            return animal;
        }
        Animal* operator->()
        {
            return animal;
        }
    };

    iterator begin()
    {
        return iterator(wrappers.begin(), wrappers.end());
    }
    iterator end()
    {
        return iterator(wrappers.end(), wrappers.end());
    }

    template <typename T>
    void push_back(std::vector<T*>& v)
    {
        wrappers.emplace_back(new SpecificWrapper<decltype(v)>(v));
    }
};

到目前为止,我只实现了一个前向迭代器,可以提供更多的运算符来进行双向甚至随机访问。此外,我们可能会添加const迭代器,(const)反向迭代器,...

答案 2 :(得分:0)

您可以创建您的狗矢量:

vector<Animal*> dogs;

在插入之前投射你的狗对象

dogs.push_back((Animal*)new Dog());

稍后,在访问

时退回

答案 3 :(得分:0)

你可以毫无问题地做你真正想做的事!也就是说,只需:

class Animal {
   public:
      std::string GetNoise() const = 0;
};
class Dog : public Animal {
   public:
      std::string GetNoise() const { return "Bark!"; }
};
class Cat : public Animal {
   public:
      std::string GetNoise() const { return "Meow"; }
      bool        LikesSleeping() const { return true; }
};

Dog* d = new Dog;
Cat* c = new Cat;
vector<Animal*> all_animals;
all_animals.push_back(d, c);

// then, later...

// this will print "Bark!"
std::cout << all_animals[0]->GetNoise() std::endl;

// if you know the type somehow
Cat* x = dynamic_cast<Cat*>(all_animals[1]);
const bool y = x->LikesSleeping();

您的代码无法按预期方式运行的原因是:std::vector<Dog*>std::vector<Animal*>完全相同的不同类

换句话说,Dog继承自Animal,是的,std::vector<X>不会从std::vector<Y>继承 - 无论X和Y如何相关!

模板不会给矢量带来太多智能;他们只是定义了一个新类。你可以这样想:

class vectorOfDogs {
    Dog* myDogs;
    //...
}

class vectorOfAnimals {
    Animal* myAnimals;
    //...
}

来自vectorOfDogs的{​​{1}}是否在内?显然不是!但所有这一切都是将课程名称从vectorOfAnimals更改为std::vector<Dog*>