2

我需要一个std::vectorof boost::ptr_vectors。为了使它们的管理更容易,我将 boost::ptr_vector 包含在一个类 ( Zoo) 中,并为其创建了一个 std::vector ( allZoos)。看一个最小的代码来重现这个:

#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/utility.hpp>

class Animal
{
public:
    virtual char type() = 0;
};

class Cat : public Animal
{
public:
    char type() { return 1; }
};

class Zoo
{
public:
    boost::ptr_vector<Animal> animals;
};


int main()
{
    std::vector<Zoo> allZoos;

    Zoo ourCityZoo;
    ourCityZoo.animals.push_back(new Cat());

    //Uncommenting any of the lines below causes error:
    //allZoos.push_back(ourCityZoo);
    //allZoos.clear();

    return 0;
}

声明allZoos是可以的,但是调用它的任何成员函数都会导致编译器错误:(完整的错误日志太长了,没有贴出来)

C2259: 'Animal' : cannot instantiate abstract class c:\boost_1_49_0\boost\ptr_container\clone_allocator.hpp 34  1

这与 boost 的不可复制实用程序类和自定义new_clone函数无关,我尝试了它们但没有运气。那怎么解决?

(我使用的是VS2010)

4

1 回答 1

9

实际上,阅读错误出现的位置会有所帮助。在 Boost 源代码中清楚明确地说明了这一点:

template< class T >
inline T* new_clone( const T& r )
{
    //
    // @remark: if you get a compile-error here,
    //          it is most likely because you did not
    //          define new_clone( const T& ) in the namespace
    //          of T.
    //
    T* res = new T( r );
    BOOST_ASSERT( typeid(r) == typeid(*res) &&
                  "Default new_clone() sliced object!" );
    return res;
}

如果您没有指定克隆类型的方法,它将尝试通过简单地复制它来实现,这对于抽象类是不可能的。在其命名空间中添加一个适当的clone方法abstract_class和一个new_clone函数,你会没事的。

是您的代码的固定版本。

于 2012-03-10T09:10:18.720 回答