存储和加载的 CObjects 和存档需要通过额外的注意事项。 在某些情况下,您应调用对象的 Serialize 函数,CArchive 对象是 Serialize 调用参数,而不是使用 CArchive的 << 或 >> 运算符相反。 需要谨记的重要情况为 CArchive >> 运算符构造在根据 CRuntimeClass 信息内存的 CObject 以前写入文件由存储的存档。
因此,无论是使用 CArchive <<,然后 >> 运算符,与调用 Serialize,确定是否 需要 将存档动态地重新构造基于以前存储的信息的 CRuntimeClass 对象。 在 Serialize 例子中,添加以下函数:
将反序列化对象,则预先知道对象的具体类。
将反序列化对象时,已经为其分配的内存。
警告
使用 Serialize 函数,则加载对象,使用 Serialize 函数,还必须存储对象。使用 Serialize 函数,使用 CArchive >> 运算符,请不要使用 CArchive 存储<< 运算符然后加载要或存储然后加载要使用 Serialize 函数。
以下示例演示了该例子。
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
}
}
总之,序列化定义了,则类嵌入的 t 为 CObjec成员,则 不应为该对象使用 CArchive << 和 >> 运算符,而应调用 Serialize 函数。 此外,如果可序列化,类定义一个指向 CObject (或从 CObject派生的对象。) 为成员,即,但构造在其自己的构造函数,因此上述其他对象还应调用 Serialize。