1.编写可序列化的类,继承自cobject
2.DECLARE_SERIAL 声明
3.serialize 函数
4.IMPLEMENT_SERIAL
可序列化类的版本号
——Dlg.cpp 文件中加入两个按钮,分别为存储和加载
void CDarDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
int a, b;
a = 10;
b = 100;
CFile file(_T("demo1.txt"), CFile::modeCreate | CFile::modeWrite);
CArchive ar(&file, CArchive::store);
ar << a << b;
CLine line(CPoint(1,1),CPoint(6,6));
//ar << line;
line.Serialize(ar);
ar.Close();
file.Close();
MessageBox(_T("序列化成功!!!"));
}
void CDarDlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
CFile file(_T("demo1.txt"), CFile::modeRead);
CArchive ar(&file, CArchive::load);
int a, b;
CLine line;
ar >> a >> b;
line.Serialize(ar);
m_edit_text.Empty();
CString s;
s.Format(_T("a=%d\r\n"), a);
m_edit_text.Append(s);
s.Format(_T("b=%d\r\n"), b);
m_edit_text.Append(s);
s.Format(_T("Line from=(%d,%d) to=(%d,%d)\r\n"), line.m_ptFrom.x, line.m_ptFrom.y, line.m_ptTo.x, line.m_ptTo.y);
m_edit_text.Append(s);
ar.Close();
file.Close();
UpdateData(FALSE);
/*UpdateData(TRUE)的作用是将文本框界面值跟新到控件变量;
UpdateData(FALSE)的作用是将控件变量的值更新到界面中。*/
}
line.h 写序列化类
#pragma once
#include "pch.h"
//
//CArchive串行化,序列化
//
//1.编写可序列化的类,继承自cobject
//2.DECLARE_SERIAL 声明
//3.serialize 函数
//4.IMPLEMENT_SERIAL
//可序列化类的版本号
class CLine :public CObject
{
DECLARE_SERIAL(CLine)
public:
CPoint m_ptFrom;
CPoint m_ptTo;
public:
CLine(){}
CLine(CPoint from, CPoint to)
{
m_ptFrom = from;
m_ptTo = to;
}
void Serialize(CArchive &ar);
};
line.cpp 写序列化函数
#include "pch.h"
#include "line.h"
IMPLEMENT_SERIAL(CLine, CObject, 1);
void CLine::Serialize(CArchive &ar)
{
CObject::Serialize(ar);
if (ar.IsStoring())
{
ar << m_ptFrom << m_ptTo;
}
else
{
ar >> m_ptFrom >> m_ptTo;
}
}