您的位置:首页 > 其它

测试了下boost的序列化反序列化功能

2017-10-07 21:13 411 查看
[cpp] view plain copy

// testSerialization.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#include <boost/archive/text_oarchive.hpp>

#include <boost/archive/text_iarchive.hpp>

#include <boost/serialization/vector.hpp>

#include <string>

#include <vector>

#include <iostream>

#include <sstream>

#include <fstream>

/*

标题:boost的序列化反序列化功能测试

环境:VS2010sp1、boost 1.55

参考资料:

[1]《Boost中支持序列化反序列化的库--boost.serialization 》
http://blog.csdn.net/oracleot/article/details/4280084
[2]《What does BOOST_SERIALIZATION_NVP do when serializing object?》
http://stackoverflow.com/questions/8532331/what-does-boost-serialization-nvp-do-when-serializing-object
*/

struct MyRecord

{

std::string a;

std::string b;

//为使当前的结构能支持序列化,得加入下面的代码段

private:

friend class boost::serialization::access;

template<class Archive>

void serialize(Archive & ar, const unsigned int version)

{

ar & a;

ar & b;

}

};

struct MyData{

int id;

std::string strName;

std::string strValue;

MyData() {}

MyData(int id, std::string strName, std::string strValue)

{

this->id = id;

this->strName = strName;

this->strValue = strValue;

}

std::vector<MyRecord> listMR;

private:

friend boost::serialization::access; //声明友元,授予访问权限

template<typename Archive>

void serialize(Archive &ar,const unsigned int version) //序列化函数

{

ar & id;

ar & strName & strValue;

ar & listMR;

}

};

void printTest(MyData &mt)

{

std::cout<<"a="<<mt.id<<" uid="<<mt.strName.c_str()<<" usr="<<mt.strValue.c_str()<<std::endl;

std::vector<MyRecord>::iterator iter = mt.listMR.begin();

while(iter!=mt.listMR.end())

{

std::cout<<"=> "<<iter->a.c_str()<<" "<<iter->b.c_str()<<std::endl;

iter++;

}

}

int _tmain(int argc, _TCHAR* argv[])

{

std::stringstream ss;

//序列化

MyData p1(11,"anderson","neo"); //被序列化的对象

//为被序列化对象添加两条记录

MyRecord mr,mr2;

mr.a="apple",mr.b="第一条记录";

mr2.a = "this is b",mr2.b = "第二条记录";

p1.listMR.push_back(mr);

p1.listMR.push_back(mr2);

boost::archive::text_oarchive(ss) << p1; //序列化

//序列化为xml形式要求中文为utf-8编码,否则打开文件是乱码

//std::stringstream ss;

//std::ofstream ofs("d:\\a.xml");

//boost::archive::xml_oarchive oa(ofs);

//oa << BOOST_SERIALIZATION_NVP(p1);

//反序列化

MyData p2; //被反序列化的对象

boost::archive::text_iarchive(ss) >> p2; //反序列化

printTest(p2);

std::cout << "序列化后的=>" << ss.str() << std::endl;;

return 0;

}
http://blog.csdn.net/lee353086/article/details/38421095
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: