CObject를 상속한 객체의 .Serialize()에 인자로 넘겨주면 해당 객체가 스스로(?) 직렬화한다.
CArchive()
1. CObject 클래스로부터 직접 또는 간접적으로 상속을 받는다.
2. 생성자 함수를 만든다. // 객체 초기화
3. 헤더 파일에 DECLARE_SERIAL
4. 소스 파일에 IMPLEMENT_SERIAL
TRY
{
CFile file;
file.Open(_T ("..."), CFile::modeCreate|CFile::modeWrite);
/*
CFile file (_T ("..."), CFile::modeRead);
*/
CArchive ar(&file, CArchive::store);
ar << a << b;
/*
CArchive ar(&file, CArchive::load)
ar >> a >> b;
*/
ar << nCount;
for (int i=0; i<nCount; i++)
ar << pLines[i];
/*
ar >> nCount;
for (int i=0; i<nCount; i++)
ar >> pLines[i];*/
}
CATCH(CFileException, e)
{
e->ReportError();
}
END_CATCH
class CLine : public CObject
{
DECLARE_SERIAL(CLine)
protected:
CPoint m_ptFrom;
CPoint m_ptTo;
COLORREF m_clrLine;
public:
CLine() {}
CLine(CPoint from, CPoint to, COLORREF color)
{ m_ptFrom = from; m_ptTo = to; m_clrLine = color; }
void Serialize(CArchive &ar);
};
IMPLEMENT_SERIAL(CLine, CObject, 2 | VERSIONABLE_SCHEMA)
void CLine::Serialize(CArchive &ar)
{
CObject::Serialize(ar);
if (ar.IsStoring())
ar << m_ptFrom << m_ptTo;
else {
UINT nSchema = ar.GetObjectSchema();
switch(nSchema) {
case 1:
ar >> m_ptFrom >> m_ptTo;
m_clrLine = RGB(0,0,0);
break;
case 2:
ar >> m_ptFrom >> m_ptTo >> m_clrLine;
break;
default:
AfxThrowArchiveException(CArchiveException::badSchema);
break;
}
}
}
CLine line(CPoint(0, 0), CPoint(100, 50));
ar << &line;
CLine *pLine;
ar >> pLine;
CLine line = *pLine; // Assumes CLine has a copy constructor.
delete pLine;