序列化(boost serialization)--類內部定義序列化方法
#include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <string> #include <fstream>
struct employee { int id; int age; std::string name; employee() :id(0),age(0),name("") {} employee(int id_,int age_, std::string name_) :id(id_),age(age_),name(name_) {}
template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & id; ar & age; ar & name; } }; void save(const employee& es) { std::ofstream ofs("data"); boost::archive::text_oarchive oa(ofs); oa << es; }
void load(employee& es) { std::ifstream ifs("data"); boost::archive::text_iarchive ia(ifs); ia >> es; }
int main(int argc, char ** argv) { employee e1(10,20, "123131"); save(e1); employee e2; load(e2); return 0; }
編譯:
g++ t.cpp -lboost_serialization
執行結果:
22 serialization::archive 10 0 0 10 20 6 123131