CArchive使用举例

来源:互联网 发布:windows切换苹果系统 编辑:程序博客网 时间:2024/04/28 13:41

今天学习下类的串行化,举个例子记录下。

先参考一篇文章:http://blog.csdn.net/candyliuxj/article/details/6782172,学习如何增加串行化

一、MFC允许对象在程序运行的整个过程中持久化的串行化机制

(1)串行化是指向持久化存储媒介(如一个磁盘文件)读或写对象的过程。

(2)串行化用于在程序运行过程时或之后修复结构化数据(如C++类或结构)的状态。

(3)MFC支持CObject类中的串行化,所以,所有继承于CObject的类可以利用CObject的串行化协议。

(4)串行化的基本思想:

          a、对象必须能将其当前状态写入到持久化存储媒介中,通常用其成员变量实现。

          b、对象可以通过读或反序列化从存储媒介中重新构造对象的状态。

          c、串行化处理所有对象指针的细节,以及序列化对象时对对象的循环引用。

          d、关键点是对象自己负责读和写其本身的状态,所以,序列化一个对象时,必须是想基本的序列化操作。

(5)MFC使用CArchive类的对象作为被序列化的对象和存储媒介之间的中间媒介。

二、生成一个可串行化的类的步骤

(1) Derive your class from CObject. (定义一个基类为CObject的类)

(2) Override the Serialize member function.(重写串行化函数)

(3) Use the DECLARE_SERIAL macro in the class declaration.(在类声明文件中使用DECLARE_SERIAL宏)

(4) Define a constructor with no arguments (a default constructor).(定义一个无参数的构造函数)

(5) Use the IMPLEMENT_SERIAL macro in the class implementation file.(在实现文件中使用IMPLEMENT_SERIAL宏)

三、实例

Graph.h文件

<span style="font-size:10px;">#ifndef _GRAPH_H#define _GRAPH_H</span>
<span style="font-size:10px;">#include "afx.h"#include "afxwin.h"class Graph : public CObject  ////(1)定义一个基类为COject的类  {  //    DECLARE_SERIAL(Graph)  ////(3)在类声明文件中使用DECLARE_SERIAL宏  public:      Graph(); ////(4)定义一个无参数的构造函数      Graph(int drawType, int ptOld);      virtual ~Graph();          void Serialize(CArchive &ar);// //(2)重写串行化函数      private:      int m_drawType;      int m_ptOld;  };#endif</span>

Graph.cpp:

<span style="font-size:10px;">#include "graph.h" IMPLEMENT_SERIAL(Graph, CObject, 1) //(5)在实现文件中使用IMPLEMENT_SERIAL宏  Graph::Graph() //(4)定义一个无参数的构造函数  {  }  Graph::Graph(int drawType, int ptOld)  {      this->m_drawType = drawType;      this->m_ptOld = ptOld;  }  Graph::~Graph()  {  }  // Graph 成员函数  void Graph::Serialize(CArchive &ar) //(2)重写串行化函数  {      CObject::Serialize(ar);    if (ar.IsStoring())      {          ar<<m_drawType<<m_ptOld;      }      else      {          ar>>m_drawType>>m_ptOld;      }  }  </span><span style="font-size: 14px;"></span>

其次, 我们再写一个主程序调用这个例子。

MainDebug.cpp:

#include "graph.h"void main(){    // save a object    CFile file1("file.txt", CFile::modeWrite | CFile::modeCreate);    CArchive ar1(&file1, CArchive::store);    Graph *gh1=new Graph(1,2);    try    {        ar1<<gh1;    }    catch(CException *e)    {        e->Delete();    }    ar1.Close();    file1.Close();    // read a object    CFile file2("file.txt", CFile::modeRead | CFile::modeCreate | CFile::modeNoTruncate );    CArchive ar2(&file2, CArchive::load);    Graph *gh2 = NULL;    try    {        ar2>>gh2;    }    catch(CException *e)    {        e->Delete();    }    ar2.Close();    file2.Close();}




0 0