首页 > 代码库 > 关于序列化:把某个对象序列化成字节流

关于序列化:把某个对象序列化成字节流

在网络编程中,一个经常的操作是将本地的数据块转换成字符流并将其发送到远端,远端将这个字符串流恢复成数据库。假设有如下一个类CObject,编写两个函数,分别将CObject中的成员变量转换为一个字符流(convert2Stream()函数),并将字符流的数据重新恢复到一个CObject对象中(convert2Object()函数):

char* convert2Stream(const CObject* vObject);

CObject* convert2Object(const char* vStream);

class CObject

{

private:

int m_NumSample;

std::vector<int> m_Data;

bool m_IsDirty;

}

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <boost/assign/list_of.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/vector.hpp>  

class CObject
{
public:
	CObject() {}
	~CObject() {}

	void printMember() const
	{
		std::cout << "Number " << m_NumSample << "\n";
		std::cout << "vector: ";
		for (int i=0; i<m_Data.size(); ++i)
		{
			std::cout << m_Data[i] << " ";
		}std::cout << std::endl;
		std::cout << "bool " << m_IsDirty << std::endl;
	}

	void setValue(int vNumber, const std::vector<int>& vData, bool vB)
	{
		m_NumSample = vNumber;
		m_Data = http://www.mamicode.com/vData;>