注意点:
1. 必须类型序列化声明
DECLARE_SERIAL( Person )
2. 必须写出实现宏
IMPLEMENT_SERIAL(Person, CObject, VERSIONABLE_SCHEMA | 2)
3. 重写CObject中的Serialize函数
void Person::Serialize( CArchive& ar )
{
CObject::Serialize(ar);
//关键代码
if(ar.IsStoring()) {
//序列化
ar << this->age << this->sex << this->name;
} else {
//反序列化
ar >> this->age >> this->sex >> this->name;
}
}
序列化后的数据
- #pragma once
- #include <afx.h>
- #include <string>
- #include <atlstr.h>
-
- using namespace std;
-
- class Person: public CObject
- {
- private:
-
- CString name;
- int age;
- char sex;
- public:
- DECLARE_SERIAL( Person )
-
- Person(void);
-
- Person(CString name, int age, char sex);
-
- virtual ~Person(void);
-
- virtual void Serialize(CArchive& ar);
-
- void setName(CString pName);
-
- CString getName();
-
- void setAge(int age);
-
- int getAge();
-
- void setSex(char sex);
-
- char getSex();
- };
-
- #include "StdAfx.h"
- #include "Person.h"
- #include <afx.h>
- #include <string>
-
- IMPLEMENT_SERIAL(Person, CObject, VERSIONABLE_SCHEMA | 2)
-
- Person::Person(void)
- {
- }
-
- Person::Person( CString name, int age, char sex )
- {
- this->name = name;
- this->age = age;
- this->sex = sex;
- }
-
- Person::~Person(void)
- {
- }
-
- void Person::setName( CString name)
- {
- this->name = name;
- }
-
- CString Person::getName()
- {
- return this->name;
- }
-
- void Person::setAge( int age )
- {
- this->age = age;
- }
-
- int Person::getAge()
- {
- return this->age;
- }
-
- void Person::setSex( char sex )
- {
- this->sex = sex;
- }
-
- char Person::getSex()
- {
- return this->sex;
- }
-
- void Person::Serialize( CArchive& ar )
- {
- CObject::Serialize(ar);
-
- if(ar.IsStoring()) {
-
- ar << this->age << this->sex << this->name;
- } else {
-
- ar >> this->age >> this->sex >> this->name;
- }
- }
-
- #include "stdafx.h"
- #include <tchar.h>
- #include <afx.h>
- #include <iostream>
-
- using namespace std;
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- Person person;
- person.setAge(20);
- person.setName("zhangsan");
- person.setSex(‘1‘);
-
- CFile myFile(_T("c:/person.ser"), CFile::modeCreate | CFile::modeReadWrite);
-
- CArchive arStore(&myFile, CArchive::store);
-
-
- arStore.WriteObject(&person);
-
- arStore.Flush();
-
- arStore.Close();
-
-
- myFile.SeekToBegin();
- CArchive arLoad(&myFile, CArchive::load);
-
-
- Person* p = (Person*) arLoad.ReadObject(person.GetRuntimeClass());
- arLoad.Close();
-
-
-
- CString name = p->getName();
- wchar_t* pch = name.GetBuffer(0);
- wcout << "姓名:" << pch << endl;
- name.ReleaseBuffer();
-
- cout << "性别:" << p->getSex() << endl;
- cout << "年龄:" << p->getAge() << endl;
-
- delete p;
- return 0;
- }