【MFC】序列化(Serialize)、反序列化(Deserialize)

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 | 2) //必要内容

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;

}

 

你可能感兴趣的:(Serialize)