共用方式為


透過封存儲存及載入 CObjects

藉由封存儲存和載入 CObject 需要額外的考量。 在一些情況下,您應該呼叫物件的 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。

請參閱

概念

序列化:序列化物件