实例类库定义

实例类库定义

  1. Book.h
  2. #include <afxwin.h>
  3. class CBook : public CObject
  4. {
  5.  DECLARE_SERIAL(CBook)
  6.  public:
  7.   CString m_strName;
  8.   CString m_strAuthor;
  9.   CString m_strPress;
  10.  public:
  11.   CBook(){}
  12.   CBook(CString strName, CString strAuthor, CString strPress)
  13.   {
  14.    m_strName = strName; // 书名
  15.    m_strAuthor = strAuthor; // 作者
  16.    m_strPress = strPress; // 出版社
  17.   }
  18.   void Serialize(CArchive &); // 重载基类的Serialize函数
  19. };
  20. Book.cpp
  21. #include "Book.h"
  22. IMPLEMENT_SERIAL(CBook, CObject, 1)
  23. void CBook::Serialize(CArchive &ar)
  24. {
  25.  CObject::Serialize(ar);
  26.  if(ar.IsStoring())
  27.  {
  28.   ar << m_strName << m_strAuthor << m_strPress;
  29.  }
  30.  else
  31.  {
  32.   ar >> m_strName >> m_strAuthor >> m_strPress;
  33.  }
  34. }

调用程序方法

  1. CBook book1("Programming Windows""Charles Petzold""Microsoft Press");
  2. CBook book2("Programming Windows with MFC""Jeff Prosise""Microsoft Press");
  3. int nCount = 2;
  4. // 序列化
  5. CFile fileStore(_T("mybooks.dat"), CFile::modeWrite | CFile::modeCreate);
  6. CArchive arStore(&fileStore, CArchive::store);
  7. CBook* pBooksStore[2] = { &book1, &book2 };
  8. arStore << nCount;
  9. for (int i=0; i<nCount; ++i)
  10. {
  11.  arStore << pBooksStore[i];
  12. }
  13. fileStore.Close();
  14. // 反序列化
  15. CFile fileLoad(_T("mybooks.dat"), CFile::modeRead);
  16. CArchive arLoad(&fileLoad, CArchive::load);
  17. arLoad >> nCount;
  18. CBook* pBooksLoad = new CBook[nCount];
  19. for (int i=0; i<nCount; ++i)
  20. {
  21.  arLoad >> pBooksLoad[i];
  22. }
  23. fileLoad.Close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值