Hos*_*ein 2 c++ polymorphism abstract-class vector ptr-vector
我需要有一个std::vector的boost::ptr_vector秒.为了简化管理,我将boost :: ptr_vector包含在一个class(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;
}
Run Code Online (Sandbox Code Playgroud)
声明allZoos是可以的,但调用其任何成员函数会导致编译器错误:(完整错误日志太长,未发布)
C2259: 'Animal' : cannot instantiate abstract class c:\boost_1_49_0\boost\ptr_container\clone_allocator.hpp 34 1
Run Code Online (Sandbox Code Playgroud)
这与boost的new_clone不可复制的实用程序类和自定义函数无关,我尝试了它们没有运气.怎么解决这个问题?
(我正在使用VS2010)
实际上,阅读错误出现的位置会有所帮助.在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;
}
Run Code Online (Sandbox Code Playgroud)
如果您没有指定克隆类型的方法,它将尝试通过简单地复制它来实现,这对于抽象类是不可能的.在命名空间中添加一个适当的clone方法abstract_class和new_clone函数,你会没事的.
这是您的代码的固定版本.
| 归档时间: |
|
| 查看次数: |
1113 次 |
| 最近记录: |