【MFC】序列化(Serialize)、反序列化(Deserialize)
2024-08-25 13:40:22
1、首先在头文件里面声明
DECLARE_SERIAL(CSelectionSerial)
2、重写CObject的Serialize函数
virtual void Serialize(CArchive& ar)
{
CObject::Serialize(ar);
//关键代码
if(ar.IsStoring())
{
//序列化
ar << this->xxx;
}
else
{
//反序列化
ar >>xxx;
}
}
3、在类开始出定义
IMPLEMENT_SERIAL(Person, CObject, VERSIONABLE_SCHEMA | 2)
下面给出一个列子:
1、序列化类.h文件
#pragma once // CSelectionSerial 命令目标
class CSelectionSerial : public CObject
{
public:
DECLARE_SERIAL(CSelectionSerial) //必要内容
CSelectionSerial();
virtual ~CSelectionSerial();
//序列化重写
//参数ar,CArchive类型
virtual void Serialize(CArchive& ar); //必要内容
void SetCurrent(const int index);
int GetCurrent();
void SetFile(const CString file);
CString GetFile();
private:
int m_Current;
CString m_File;
};
2、序列化类.cpp文件
// SelectionSerial.cpp : 实现文件
// #include "stdafx.h"
#include "SelectionSerial.h" // CSelectionSerial
IMPLEMENT_SERIAL(CSelectionSerial,CObject,VERSIONABLE_SCHEMA | ) //必要内容
CSelectionSerial::CSelectionSerial()
{
} CSelectionSerial::~CSelectionSerial()
{
} // CSelectionSerial 成员函数 void CSelectionSerial::Serialize(CArchive& ar) //必要内容
{
CObject::Serialize(ar);
if(ar.IsStoring())
{
//序列化
ar<<this->m_File;
ar<<this->m_Current;
}
else
{
//反序列化
ar>>this->m_File;
ar>>this->m_Current;
}
} void CSelectionSerial::SetCurrent(int index)
{
m_Current=index;
} int CSelectionSerial::GetCurrent()
{
return m_Current;
}
void CSelectionSerial::SetFile(CString file)
{
m_File=file;
} CString CSelectionSerial::GetFile()
{
return m_File;
}
3、序列化
void Serializable(CSelectionSerial* serial,CString filePath)
{
CFile file(filePath,CFile::modeCreate|CFile::modeWrite);
file.SeekToBegin();
::CArchive arStore(&file,CArchive::store);
arStore.WriteObject(serial);
arStore.Flush();
arStore.Close();
file.Close();
}
4、反序列化
CSelectionSerial* DeSerializable(CString filePath)
{
CFile file(filePath,CFile::modeRead);
file.SeekToBegin();
::CArchive arLoad(&file,CArchive::load);
CSelectionSerial* serial = (CSelectionSerial*)arLoad.ReadObject(RUNTIME_CLASS(CSelectionSerial));
arLoad.Close();
file.Close();
return serial;
}
最新文章
- PHP session
- java compiler level does not match the version of the installed java project facet
- silverlight: http请求的GET及POST示例
- html、css、js文件加载顺序及执行情况
- 在ubuntu下安装phpmyadmin 出现404错误
- php 安装redis扩展
- iOS开发——图层OC篇&;Quartz 2D各种绘制实例
- ArrowDrawable
- win7上帝模式
- XI.spring的点点滴滴--IObjectFactoryPostProcessor(工厂后处理器)
- 作为iOS开发者不得不follow的52人
- IP头,TCP头,UDP头,MAC帧头定义(转)
- spring+springmvc+mybaties整合实例
- redhat下yum命令安装(替换为centos yum命令)
- 什么是ObjCTypes?
- 11_Python文件操作
- 0428-css样式
- throws与throw
- 18.python关于mysql的api
- HttpWebRequst中https的验证处理问题
热门文章
- Force.com微信企业号开发系列(一) - 启用二次验证
- 2015年第2本(英文第1本):《The Practice of Programming》
- 【读书笔记】iOS网络-HTTP-URL百分号编码
- 基础学习day03---程序结构与控制、函数与数组入门
- Android Activity使用拾遗
- iOS开发笔记10:圆点缩放动画、强制更新、远程推送加语音提醒及UIView截屏
- 问题解决——SolidWorks 已停止工作 (Windows7 + SolidWorks 2010 SP0.0)
- nyoj 284 坦克大战 简单搜索
- ffmpeg编译x264, 这个libffmpeg即可解码又可以h264编码
- python Basic usage