Person.h
class CPerson : public CObject
{
DECLARE_SERIAL(CPerson) //---第一步,定义宏
public:
CPerson(void); //第二步,定义无参构造函数
CPerson(CString name, int age, bool gender = true); //第三,带参数的构造函数
virtual void Serialize(CArchive& ar); //第四步,重写序列化函数
virtual ~CPerson(void);
CString m_name;
int m_age;
bool m_gender;
private:
CString m_words;
};
Person.Cpp
#include "StdAfx.h"
#include "CPerson.h"
CPerson::CPerson(void)
{
m_name = _T("hi");
m_age = 0;
m_gender = true;
}
CPerson::CPerson(CString name, int age, bool gender)
{
m_name = name;
m_age = age;
m_gender = gender;
}
void CPerson::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
ar << this->m_name << this->m_age << this->m_gender << this->m_words;
}
else
{
ar >> this->m_name >> this->m_age >> this->m_gender >> this->m_words;
}
}
CPerson::~CPerson(void)
{
}
IMPLEMENT_SERIAL(CPerson, CObject, 1) //第五步,实现宏
使用的时候:
void CAboutDlg::OnBnClickedSer()
{
CFile file(_T("D:/persons.archive"), CFile::modeCreate | CFile::modeWrite);
CArchive ar(&file, CArchive::store);
CPerson p(_T("aaa"),1,true);
// TODO: add storing code here
ar<<&p;
ar.Close();
file.Close();
// TODO: add loading code here
// TODO: Add your control notification handler code here
//OnOK();
}
void CAboutDlg::OnBnClickedDeser()
{
CFile Rfile(_T("D:/persons.archive"), CFile::modeRead);
CArchive Rar(&Rfile, CArchive::load);
CPerson* p1;
//序列化出来
Rar >> p1 ;
AfxMessageBox(p1->m_name);
// TODO: Add your control notification handler code here
}