共用方式為


儲存及載入 CObjects 透過保存

儲存及載入CObjects 透過保存需要額外的考量。 在某些情況下,您應該呼叫Serialize函式的物件,其中CArchive物件是參數的Serialize呼叫,相較於使用 <<>> 運算子的CArchive。 要牢記在心的重要事實是, CArchive>> 運算子建構CObject為基礎的記憶體中CRuntimeClass在儲存保存先前寫入至檔案的資訊。

因此,您是否使用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。

請參閱

概念

序列化: 序列化物件