对象串行化的方法和步骤1、将要串行化对象的类派生于object。 class CPerson : public CObject {2、给串行化对象的类添加 void CPerson::Serialize( CArchive& archive )成员函数 void CPerson::Serialize( CArchive& archive ) { // call base class function first // base class is CObject in this case CObject::Serialize( archive ); // now do the stuff for our specific class if( archive.IsStoring() ) archive << m_name << m_number; else archive >> m_name >> m_number; }3、类头文件中声明 DECLARE_SERIAL( CGraph ) class CPerson : public CObject { DECLARE_SERIAL( CPerson ) // rest of declaration follows... }; 4、//4需要一个空的构造函数 class CPerson : public CObject { CPerson(); 5、类的实现文件(cpp)中的声明 IMPLEMENT_SERIAL( CPerson, CObject, 1 )串行化过程:保存对象myCperson到硬盘: CPerson myCperson; //对象操作部分 CFile file("file.dat",CFile::modeCreate|CFile::modeWrite); CArchive ar(&file,CArchive::store);if (ar.IsStoring()) { ar<<myCperson;
class CPerson : public CObject
{2、给串行化对象的类添加 void CPerson::Serialize( CArchive& archive )成员函数
void CPerson::Serialize( CArchive& archive )
{
// call base class function first
// base class is CObject in this case
CObject::Serialize( archive ); // now do the stuff for our specific class
if( archive.IsStoring() )
archive << m_name << m_number;
else
archive >> m_name >> m_number;
}3、类头文件中声明 DECLARE_SERIAL( CGraph )
class CPerson : public CObject
{
DECLARE_SERIAL( CPerson )
// rest of declaration follows...
};
4、//4需要一个空的构造函数
class CPerson : public CObject
{
CPerson();
5、类的实现文件(cpp)中的声明
IMPLEMENT_SERIAL( CPerson, CObject, 1 )串行化过程:保存对象myCperson到硬盘:
CPerson myCperson;
//对象操作部分
CFile file("file.dat",CFile::modeCreate|CFile::modeWrite);
CArchive ar(&file,CArchive::store);if (ar.IsStoring())
{
ar<<myCperson;
}反串行化过程:CFile file("file.dat", CFile::modeRead);
CArchive ar(&file,CArchive::load);
CGraph m_g;
if (ar.IsLoading())
{
ar>>m_g;
}
//对象操作部分