实例类库定义
- Book.h
- #include <afxwin.h>
- class CBook : public CObject
- {
- DECLARE_SERIAL(CBook)
- public:
- CString m_strName;
- CString m_strAuthor;
- CString m_strPress;
- public:
- CBook(){}
- CBook(CString strName, CString strAuthor, CString strPress)
- {
- m_strName = strName; // 书名
- m_strAuthor = strAuthor; // 作者
- m_strPress = strPress; // 出版社
- }
- void Serialize(CArchive &); // 重载基类的Serialize函数
- };
- Book.cpp
- #include "Book.h"
- IMPLEMENT_SERIAL(CBook, CObject, 1)
- void CBook::Serialize(CArchive &ar)
- {
- CObject::Serialize(ar);
- if(ar.IsStoring())
- {
- ar << m_strName << m_strAuthor << m_strPress;
- }
- else
- {
- ar >> m_strName >> m_strAuthor >> m_strPress;
- }
- }
调用程序方法
- CBook book1("Programming Windows", "Charles Petzold", "Microsoft Press");
- CBook book2("Programming Windows with MFC", "Jeff Prosise", "Microsoft Press");
- int nCount = 2;
- // 序列化
- CFile fileStore(_T("mybooks.dat"), CFile::modeWrite | CFile::modeCreate);
- CArchive arStore(&fileStore, CArchive::store);
- CBook* pBooksStore[2] = { &book1, &book2 };
- arStore << nCount;
- for (int i=0; i<nCount; ++i)
- {
- arStore << pBooksStore[i];
- }
- fileStore.Close();
- // 反序列化
- CFile fileLoad(_T("mybooks.dat"), CFile::modeRead);
- CArchive arLoad(&fileLoad, CArchive::load);
- arLoad >> nCount;
- CBook* pBooksLoad = new CBook[nCount];
- for (int i=0; i<nCount; ++i)
- {
- arLoad >> pBooksLoad[i];
- }
- fileLoad.Close();