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