MFC序列化与反序列化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#pragma once #include "afx.h" #include <vector> using std::vector; class HzyData : public CObject { public: HzyData(); ~HzyData(); public: DECLARE_SERIAL(HzyData) virtual void Serialize(CArchive& ar); void initail(); void testData(); private: int dInt; double dDouble; CString dStr; vector<double> dVec; };
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "stdafx.h" #include "HzyData.h" IMPLEMENT_SERIAL(HzyData, CObject, VERSIONABLE_SCHEMA | 2) HzyData::HzyData() { initail(); } HzyData::~HzyData() { } void HzyData::initail() { this->dInt = 0; this->dDouble = 0; this->dStr = _T(""); this->dVec.clear(); } void HzyData::testData() { this->dInt = 3; this->dDouble = 7.2; this->dStr = _T("hello,hzy"); this->dVec.clear(); for (int i = 0; i < 10; i++) { this->dVec.push_back(i * 2.3); } } void HzyData::Serialize(CArchive& ar) { CObject::Serialize(ar); //关键代码 if (ar.IsStoring()) { //序列化 ar << this->dInt << this->dDouble << this->dStr; int size = (int)this->dVec.size(); ar << size; for (int i = 0; i < size; i++) { ar << this->dVec[i]; } } else { //反序列化 ar >> this->dInt >> this->dDouble >> this->dStr; int size = 0; ar >> size; this->dVec.clear(); for (int i = 0; i < size; i++) { double temp = 0; ar >> temp; dVec.push_back(temp); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
HzyData data; data.testData(); CFile myFile(_T("d:/hzydata.ser"), CFile::modeCreate | File::modeReadWrite); CArchive archive(&myFile, CArchive::store); data.Serialize(archive); archive.Close(); myFile.Close();
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
CFile myFile(_T("d:/hzydata.ser"), CFile::modeRead); CArchive archive(&myFile, CArchive::load); HzyData data; data.Serialize(archive); archive.Close(); myFile.Close();