利用boost的serialization库实现c++对象的序列化与反序列化
来源:互联网 发布:最好的看书软件 编辑:程序博客网 时间:2024/05/16 19:09
代码示例及讲解
#include <cstddef>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/string.hpp>//本例中需要对string进行存储,所以引入string.hpp;此外还有一些预定义的模板,如vector、list、map等
#include <boost/serialization/access.hpp>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Cat{
public:
Cat() {}//每个对象都必须提供一个默认构造函数
Cat(string name) { this->name = name; }
void print() { cout<<"my name is "<<this->name<<endl; }
string getName() { return this->name; }
void setName(string name) { this->name = name; }
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version){
ar & name;
}
string name;
};
class CatPtr{
public:
CatPtr() : c(0) {}
CatPtr(Cat c) : c(c) {}
void print() { cout<<"the cat pointed to is "<<c->getName()<<endl; }
private:
Cat *c;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version){
ar.register_type(static_cast<Cat *>(NULL));//本例中是通过Cat类的指针来使Cat对象序列化的,所以需要对该指针进行注册
ar & c;
}
};
template <class T>
void save(const T &c, string filename){
ofstream ofs(filename.c_str(),ios::app);
boost::archive::text_oarchive oa(ofs);
oa & c;
}
template <class T>
void restore(T &c, string filename){
ifstream ifs(filename.c_str());
boost::archive::text_iarchive ia(ifs);
ia & c;
}
int main(){
Cat c("Kitty");
string filename = "test.txt";
cout<<"original cat:"<<endl;
c.print();
save(c,filename);
Cat nc;
restore(nc,filename);
cout<<"new cat:"<<endl;
nc.print();
Cat *c1 = new Cat("Ann");
CatPtr cp(c1);
cp.print();
string filename = "0test.txt";
save(cp,filename);
CatPtr ncp;
restore(ncp,filename);
ncp.print();
return 0;
}
参考
http://www.boost.org/doc/libs/1_54_0/libs/serialization/doc/tutorial.html
http://www.ibm.com/developerworks/cn/aix/library/au-boostserialization/
- 利用boost的serialization库实现c++对象的序列化与反序列化
- Boost中支持序列化反序列化的库--boost.serialization
- Boost中支持序列化反序列化的库--boost.serialization
- boost serialization 序列化/反序列化 详细用法
- lintcode binary-tree-serialization 二叉树的序列化与反序列化
- 黑马程序员-面向对象多态的实现及对象序列与反序列化
- 实现对象的序列化和反序列化
- C#对象的 Xml序列化与反序列化
- Symbian 流的对象序列化与反序列化
- Symbian 流的对象序列化与反序列化
- C#中对象的序列化与反序列化
- Java 对象的序列化与反序列化实践
- 对象的序列化与反序列化
- C#中对象的序列化与反序列化
- 对象的序列化与反序列化
- C#中对象的序列化与反序列化
- 对象的序列化与反序列化
- 对象的序列化与反序列化
- poj3278Catch That Cow(BFS)
- JVM系列一:JVM内存组成及分配
- ajax常用参数
- oracle查看所有用户的表空间
- OC中并发编程的相关API和面临的挑战
- 利用boost的serialization库实现c++对象的序列化与反序列化
- 鼠标点击文本框后,里面的文字就消失,鼠标离开文本框后,里面的文字又会显示
- ios 重用UITableViewCell created from a XIB
- mfc 图像类函数定义
- 深入研究AsyncTask
- linux控制并发运行进程数
- 在ECLIPSE中使用JUNIT4.X进行单元测试
- Delphi7语言基础20130717-1
- MS-SQL生成表里数据的insert插入语句