透過封存儲存及載入 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

另請參閱

序列化:序列化物件