对象在CDocument派生类中的保存和文件I/O过程为了简化设计,在CDocument类派生类中,采用MFC提供的模板类CPtrList来保存对象。该对象定义为:
protected:
CTypedPtrList m_listPictures;
由于CTypedPtrList和CPtrList都没有实现Serialize函数,因此不能够通过ar << m_listPictures和ar >> m_listPictures 来序列化对象,因此CPictureDoc的Serialize函数需要如下实现:
void CTsDoc::Serialize(CArchive& ar)
{
POSITION pos;
if (ar.IsStoring())
{
// TODO: add storing code here
pos = m_listPictures.GetHeadPosition();
while(pos != NULL)
{
ar << m_listPictures.GetNext (pos);
}
}
else
{
// TODO: add loading code here
RemoveAll();
CPicture * pPicture;
do{
try
{
ar >> pPicture;
TRACE("Read Object %d\n",pPicture->GetType ());
m_listPictures.AddTail(pPicture);
}
catch(CException * e)
{
e->Delete ();
break;
}
}while(pPicture != NULL);
}
m_pCurrent = NULL;
SetModifiedFlag(FALSE);
}
实现派生类的串行化功能几何图形程序支持直线、矩形、三角形、椭圆等图形,分别以类CLine、CRectangle、CTriangle和CEllipse实现。以类CLine为例,实现串行化功能:
CPoint m_ptStart,m_ptEnd;
DECLARE_SERIAL(CLine)
void CLine::Serialize(CArchive & ar)
{
CPicture::Serialize(ar);
if(ar.IsLoading())
{
ar>>m_ptStart.x>>m_ptStart.y>>m_ptEnd.x>>m_ptEnd.y;
}else{
ar<<m_ptStart.x<<m_ptStart.y<<m_ptEnd.x<<m_ptEnd.y;
}
}
IMPLEMENT_SERIAL(CLine,CPicture,TYPE_LINE);
这样定义的CLine就具有串行化功能,其他图形类可以类似定义。
附注本文仓促草就,不足之处在所难免。请发现谬误者给我来信说明,谢谢。





