参考:孙鑫C++视频第十三讲
一、建立一个串行化类的五个步骤(参考MSDN:CObject::Serilize)
1、建立一个可串行化类,可串行化类都是从CObject继承而来
2、重载Serialize成员函数
3、在类声明中使用DECLARE_SERIAL宏
4、定义一个没有参数的构造函数
5、在实现文件中使用IMPLEMENT_SERIAL宏
二. 实例
Graph.h文件:
- #pragma once
-
-
-
- class Graph : public CObject
- {
- DECLARE_SERIAL(Graph)
- public:
- Graph();
- Graph(int drawType, CPoint ptOld);
- virtual ~Graph();
-
- void Serialize(CArchive &ar);
-
- private:
- int m_drawType;
- CPoint m_ptOld;
- };
Graph.cpp文件:
-
-
-
- #include "stdafx.h"
- #include "Archive.h"
- #include "Graph.h"
-
-
-
-
- IMPLEMENT_SERIAL(Graph, CObject, 1)
-
- Graph::Graph()
- {
- }
-
- Graph::Graph(int drawType, CPoint ptOld)
- {
- this->m_drawType = drawType;
- this->m_ptOld = ptOld;
- }
-
- Graph::~Graph()
- {
- }
-
-
- void Graph::Serialize(CArchive &ar)
- {
- if (ar.IsStoring())
- {
- ar<<m_drawType<<m_ptOld;
- }
- else
- {
- ar>>m_drawType>>m_ptOld;
- }
- }
三、CArchive类
CArchive类用来建立一个持久的disk storage.
- void CGraphicDoc::Serialize(CArchive& ar)
- {
- POSITION pos = GetFirstViewPosition() ;
- CGraphicView *pView = (CGraphicView *)GetNextView(pos) ;
- if (ar.IsStoring())
- {
-
-
-
-
-
-
-
-
-
-
-
- }
- else
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- m_obArray.Serialize(ar) ;
- }
四、如何在一个类中访问另一个类的成员
1、在Doc类中访问View类中成员获取View类指针
- POSITION pos = GetFirstViewPosition() ;
- CGraphicView *pView = (CGraphicView *)GetNextView(pos) ;
2、在View类中获取Doc类指针
- CGraphicDoc* pDoc = GetDocument();
五、删除分配的堆内存
释放分配的堆内存放在DeleteContents 虚函数中
- void CGraphicDoc::DeleteContents()
- {
-
- UINT count = m_obArray.GetSize() ;
- for(int i = 0 ; i < count ; ++ i)
- {
- delete m_obArray.GetAt(i) ;
- }
-
- m_obArray.RemoveAll() ;
-
- CDocument::DeleteContents();
- }