一、建立一个串行化类的五个步骤(参考MSDN:CObject::Serilize)
1、建立一个可串行化类,可串行化类都是从CObject继承而来
2、重载Serialize成员函数
3、在类声明中使用DECLARE_SERIAL宏
4、定义一个没有参数的构造函数
5、在实现文件中使用IMPLEMENT_SERIAL宏
二. 实例
Graph.h文件:
- #pragma once
- // Graph 命令目标
- class Graph : public CObject //(1)定义一个基类为COject的类
- {
- DECLARE_SERIAL(Graph) //(3)在类声明文件中使用DECLARE_SERIAL宏
- public:
- Graph(); //(4)定义一个无参数的构造函数
- Graph(int drawType, CPoint ptOld);
- virtual ~Graph();
- void Serialize(CArchive &ar); //(2)重写串行化函数
- private:
- int m_drawType;
- CPoint m_ptOld;
- };
Graph.cpp文件:
- // Graph.cpp : 实现文件
- //
- #include "stdafx.h"
- #include "Archive.h"
- #include "Graph.h"
- // Graph
- IMPLEMENT_SERIAL(Graph, CObject, 1) //(5)在实现文件中使用IMPLEMENT_SERIAL宏
- Graph::Graph() //(4)定义一个无参数的构造函数
- {
- }
- Graph::Graph(int drawType, CPoint ptOld)
- {
- this->m_drawType = drawType;
- this->m_ptOld = ptOld;
- }
- Graph::~Graph()
- {
- }
- // Graph 成员函数
- void Graph::Serialize(CArchive &ar) //(2)重写串行化函数
- {
- 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())//往文件中写
- {
- // TODO: 在此添加存储代码
- /*UINT i = 10 ;
- TCHAR ch = 'a' ;
- CString str(TEXT("my string")) ;
- ar<<i<<ch<<str ;*/
- /*UINT count = pView->m_obArray.GetCount() ;
- ar<<count ;
- for(int i = 0 ; i < count ; ++ i)
- {
- ar<<pView->m_obArray.GetAt(i) ;
- }*/
- }
- else//从文件中读
- {
- // TODO: 在此添加加载代码
- /*UINT i ;
- TCHAR ch ;
- CString str ;
- CString strFormat ;
- ar>>i>>ch>>str ;
- strFormat.Format(TEXT("%d %c %s") , i , ch , str) ;
- AfxMessageBox(strFormat) ;*/
- /*UINT count ;
- ar>>count ;
- CGraph *pGraph ;
- for(int i = 0 ; i < count ; ++ i)
- {
- ar>>pGraph ;
- pView->m_obArray.Add(pGraph) ;
- }*/
- }
- m_obArray.Serialize(ar) ;//M_obArray的Serialize成员是基类的
- }
1、在Doc类中访问View类中成员获取View类指针
- POSITION pos = GetFirstViewPosition() ;
- CGraphicView *pView = (CGraphicView *)GetNextView(pos) ;
2、在View类中获取Doc类指针
- CGraphicDoc* pDoc = GetDocument();
五、删除分配的堆内存
释放分配的堆内存放在DeleteContents 虚函数中
- void CGraphicDoc::DeleteContents()
- {
- // TODO: 在此添加专用代码和/或调用基类
- UINT count = m_obArray.GetSize() ;
- for(int i = 0 ; i < count ; ++ i)
- {
- delete m_obArray.GetAt(i) ;
- }
- m_obArray.RemoveAll() ;
- CDocument::DeleteContents();
- }