参考:孙鑫C++视频第十三讲
一、建立一个串行化类的五个步骤(参考MSDN:CObject::Serilize)
1、建立一个可串行化类,可串行化类都是从CObject继承而来
2、重载Serialize成员函数
3、在类声明中使用DECLARE_SERIAL宏
4、定义一个没有参数的构造函数
5、在实现文件中使用IMPLEMENT_SERIAL宏
二、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();
}