存储和加载的CObjects通过存档

存储和加载 CObjects 通过存档需要额外的注意事项。 在某些情况下,您应调用对象的 Serialize 功能, CArchive 对象是 Serialize 的参数调用,使用 CArchive<<>> 运算符相关。 需要注意的重要情况是 CArchive>> 运算符构造基于 CRuntimeClass 信息的内存 CObject 以前写入文件中存储存档。

因此,您是否使用 CArchive<< ,并 >> 运算符,与调用 Serialize,取决于是否 需要 加载存档动态重新生成基于以前存储的 CRuntimeClass 信息的对象。 在以下情况下使用 Serialize 功能:

  • 当反序列化对象时,您需要知道对象的具体类。

  • 当反序列化对象时,已为其分配的内存。

警告

使用 Serialize 功能,如果加载对象,使用 Serialize 功能,还必须存储对象。不要使用 CArchive<< 运算符存储然后使用 Serialize 函数填充,也不要使用 Serialize 函数存储然后使用 CArchive >> 运算符填充。

下面的示例演示用例:

class CMyObject : public CObject
{
// ...Member functions
public:
   CMyObject() { }
   virtual void Serialize( CArchive& ar );

// Implementation
protected:
   DECLARE_SERIAL( CMyObject )
};


class COtherObject : public CObject
{
   // ...Member functions
public:
   COtherObject() { }
   virtual void Serialize( CArchive& ar );

// Implementation
protected:
   DECLARE_SERIAL( COtherObject )
};


class CCompoundObject : public CObject
{
   // ...Member functions
public:
   CCompoundObject();
   ~CCompoundObject();
   virtual void Serialize( CArchive& ar );

// Implementation
protected:
   CMyObject m_myob;    // Embedded object
   COtherObject* m_pOther;    // Object allocated in constructor
   CObject* m_pObDyn;    // Dynamically allocated object
   //..Other member data and implementation

   DECLARE_SERIAL( CCompoundObject )
};
IMPLEMENT_SERIAL(CMyObject,CObject,1)
IMPLEMENT_SERIAL(COtherObject,CObject,1)
IMPLEMENT_SERIAL(CCompoundObject,CObject,1)


CCompoundObject::CCompoundObject()
{
   m_pOther = new COtherObject; // Exact type known and object already 
            //allocated.
   m_pObDyn = NULL;    // Will be allocated in another member function
            // if needed, could be a derived class object.
}

CCompoundObject::~CCompoundObject()
{
   delete m_pOther;
}

void CCompoundObject::Serialize( CArchive& ar )
{
   CObject::Serialize( ar );    // Always call base class Serialize.
   m_myob.Serialize( ar );    // Call Serialize on embedded member.
   m_pOther->Serialize( ar );    // Call Serialize on objects of known exact type.

   // Serialize dynamic members and other raw data
   if ( ar.IsStoring() )
   {
      ar << m_pObDyn;
      // Store other members
   }
   else
   {
      ar >> m_pObDyn; // Polymorphic reconstruction of persistent object 
      //load other members
   }
}

总之,因此,如果您的可序列化类定义嵌入 CObject 为成员,您不应为该对象使用 CArchive<<>> ,运算符,而应调用 Serialize 功能。 然后,因此,如果您的可序列化类定义的指针 CObject (或从 CObject派生的对象) 转换为成员,但是,构造在其自己的构造函数,则此其他对象还应调用 Serialize。

请参见

概念

序列化:序列化对象