MFC 创建可序列化的对象 Serialize用法

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
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值