0
我嘗試在boost的幫助下使用非默認構造函數序列化派生指針類。boost中的load_construct_data:放置新問題
在編譯我得到一個錯誤:
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中,我想保存並加載派生類。所以,我在開頭提到的編譯錯誤使我無法繼續。
任何提示我缺少什麼?
就是這樣。 Thanx – 2013-03-21 16:36:50
如果你很滿意你的問題的答案,你可以接受它。這有助於未來的觀衆併爲回答者提供激勵。 – rhashimoto 2013-03-22 14:47:34