我尝试在 boost 的帮助下使用非默认构造函数序列化派生指针类。
在编译过程中我得到一个错误:
Derived.h: In function ‘void boost::serialization::load_construct_data(Archive&, const A::Derived*, unsigned int)’:
in Derived.h: error: no matching function for call to ‘operator new(long unsigned int, const A::Derived*&)
我包括<new>
到Derived.h
,但我有一种我忘记做某事的感觉。这是我对代码的粗略估计。
我有一个带有虚函数和非默认构造函数的基类(在 Base.h 中)
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
namespace A{
class Base
{
public:
int getID(){return ID};
//non default constructor
Base(param1, param2, param3):ID(param1+param2), BaseFlag(param3) {};
Base(param1, param3):ID(param1), BaseFlag(param3) {};
//some virtual functions
virtual void Foo1();
virtual void Foo2();
...
private:
int ID;
bool BaseFlag;
...
//void serialize function
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
}
};
}
//end of namespace A
//implementation is in another file - exporting key
BOOST_CLASS_EXPORT_KEY(Base)
有一个派生类(在 Derived.h 中)
#include <boost/serialization/base_object.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
#include <new>
#include "Base.h"
namespace A{
//derived class
class Derived: public Base
{
public:
//non default constructor
Derived(param3):Base(param3, false);
...
private:
friend class boost::serialization::access;
template<class Archive>
// serialize base class information
void serialize(Archive & ar, const unsigned int version)
{
ar & boost::serialization::base_object<Base>(*this);
}
//prototype of save_construct_data for non-default constructor
template<class Archive> friend
void boost::serialization::save_construct_data(Archive & ar,
const Derived * t, const unsigned int file_version);
//prototype of load_construct_data for non-default constructor
template<class Archive> friend
void boost::serialization::load_construct_data(Archive & ar,
const Derived * t, const unsigned int file_version);
};
}
//end of namespace A
//export derived class
BOOST_CLASS_EXPORT_KEY(Derived)
//describe save_construct_data
namespace boost {
namespace serialization {
template<class Archive>
inline void save_construct_data(Archive & ar, const A::Derived * t, const unsigned int file_version)
{
// save data required to construct instance
ar << t->ID;
}
template<class Archive>
inline void load_construct_data(Archive & ar, const A::Derived * t, const unsigned int file_version)
{
int ID;
// load data required to construct instance
ar >> ID;
::new(t) A::Derived(ID);
}
}
}
在 main.cpp 的某个地方我想保存和加载派生类。所以,我一开始提到的编译错误阻止了我继续。
任何提示我缺少什么?