#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;
};
HzyData.h
#include "stdafx.h"
#include "HzyData.h" IMPLEMENT_SERIAL(HzyData, CObject, VERSIONABLE_SCHEMA | ) HzyData::HzyData()
{
initail();
} HzyData::~HzyData()
{
} void HzyData::initail()
{
this->dInt = ;
this->dDouble = ;
this->dStr = _T("");
this->dVec.clear();
} void HzyData::testData()
{
this->dInt = ;
this->dDouble = 7.2;
this->dStr = _T("hello,hzy");
this->dVec.clear();
for (int i = ; i < ; 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 = ; i < size; i++)
{
ar << this->dVec[i];
}
}
else {
//反序列化
ar >> this->dInt >> this->dDouble >> this->dStr;
int size = ;
ar >> size;
this->dVec.clear();
for (int i = ; i < size; i++)
{
double temp = ;
ar >> temp;
dVec.push_back(temp);
}
}
}
HzyData.cpp
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();
序列化
CFile myFile(_T("d:/hzydata.ser"), CFile::modeRead);
CArchive archive(&myFile, CArchive::load);
HzyData data;
data.Serialize(archive);
archive.Close();
myFile.Close();
反序列化