MFC的序列化技术(二)

6 篇文章 1 订阅
上面介绍了在函数中对int、float等基本数据类型的序列化,下面介绍在MFC中怎么定义支持序列化的类
一、定义一个类CStudent,从CObject公有派生,从CObject公有派生是我们自己定义的类支持序列化的一个必要条件。
class CStudent:public CObject
{

};

二、在类内和类外添加支持序列化的宏,其中类内宏的格式是DECLARE_SERIAL(类名),类外宏的格式是IMPLEMENT_SERIAL(类名,CObject,1)
class CStudent:public CObject
{
DECLARE_SERIAL(CStudent)
};
IMPLEMENT_SERIAL(CStudent,CObject,1)

三、添加类成员
class CStudent:public CObject
{
DECLARE_SERIAL(CStudent)
public:
CString m_strName;//姓名
int m_nScore;
};

四、重载void Serialize(CArchive& ar)虚函数,该函数从CObject继承而来。

class CStudent:public CObject
{
DECLARE_SERIAL(CStudent)
public:
CString m_strName;//姓名
int m_nScore;
void Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
ar<<m_strName;
ar<<m_nScore;
}
else
{
ar>>m_strName;
ar>>m_nScore;
}
}
};
IMPLEMENT_SERIAL(CStudent,CObject,1)

至此,一个支持序列化的类CStudent已经构造完成,我们可以在main函数中进行验证:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
CStudent student("Hyman",99);
BYTE* pByte=new BYTE[1024];
CMemFile file(pByte,512,128);
//序列化student信息
CArchive ar(&file,CArchive::store);
ar<<(&student);//注意这里用的是student的指针
ar.Close();
//反序列化student信息
CArchive ar1(&file,CArchive::load);
file.Seek(CFile::begin,0);
CStudent* pStu=new CStudent;
ar1>>pStu;
ar1.Close();
//打印pStu信息
cout<<"pStu->name:"<<pStu->m_strName<<endl<<"pStu->score:"<<pStu->m_nScore<<endl;
//回收资源
file.Close();
delete pStu;
delete[] pByte;
return 0;
}

总结下类支持序列化的三个必要条件:
1、该类从CObject类公有继承

2、在类内声明DECLARE_SERIAL(类名),在类外声明IMPLEMENT_SERIAL(类名,CObject,类版本号)

3、重载继承自CObject的Serialize虚函数。

源代码如下:
#include "stdafx.h"
#include "SerializeClass.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

class CStudent:public CObject
{
	DECLARE_SERIAL(CStudent)
public:
	CStudent(CString name,int Score)
	{
		m_strName=name;
		m_nScore=Score;
	}
	CStudent(){}
	CString m_strName;//姓名
	int m_nScore;
	void Serialize(CArchive& ar)
	{
		if (ar.IsStoring())
		{
			ar<<m_strName;
			ar<<m_nScore;
		} 
		else
		{
			ar>>m_strName;
			ar>>m_nScore;
		}
	}
};
IMPLEMENT_SERIAL(CStudent,CObject,1)



int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	CStudent student("Hyman",99);
	BYTE* pByte=new BYTE[1024];
	CMemFile file(pByte,512,128);
	//序列化student信息
	CArchive ar(&file,CArchive::store);
	ar<<(&student);//注意这里用的是student的指针
	ar.Close();
	//反序列化student信息
	CArchive ar1(&file,CArchive::load);
	file.Seek(CFile::begin,0);
	CStudent* pStu=new CStudent;
	ar1>>pStu;
	ar1.Close();
	//打印pStu信息
	cout<<"pStu->name:"<<pStu->m_strName<<endl<<"pStu->score:"<<pStu->m_nScore<<endl;
	//回收资源
	file.Close();
	delete pStu;
	delete[] pByte;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值