怎样令到一个Class可以有Serialize能力

五个步骤:

1.这个对象(如CPerson)派生自CObject.(ClassWizard不能生成这种类,只能直接新建类)

2.重载Serialize

3.类定义里面要写入

  DECLARE_SERIAL( CPerson )  (注意,没有分号)

4.要生成一个该类的构造函数,没有参数的.

5.类的实现里面要写入对应的

  IMPLEMENT_SERIAL( CPerson, CObject, 1 )

调用的方法:CDoc里面建立个CPerson类型的m_Obj,然后在CDoc的Serialize中有m_Obj.Serialize(ar)

-------------CPerson.h-------------------

class CPerson : public CObject
{
public:
    DECLARE_SERIAL( CPerson )
    // empty constructor is necessary
    CPerson(){};

    CString m_name;
    WORD   m_number;

    void Serialize( CArchive& archive );
   
    // rest of class declaration
};

-------------CPerson.cpp-------------------

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;
}

IMPLEMENT_SERIAL( CPerson, CObject, 1 )

你可能感兴趣的:(Serialize)