共用方式為


CArchive::MapObject

Call this member function to place objects in the map that are not really serialized to the file, but that are available for subobjects to reference.

void MapObject(
   const CObject* pOb 
);

Parameters

  • pOb
    A constant pointer to the object being stored.

Remarks

For example, you might not serialize a document, but you would serialize the items that are part of the document. By calling MapObject, you allow those items, or subobjects, to reference the document. Also, serialized subitems can serialize their m_pDocument back pointer.

You can call MapObject when you store to and load from the CArchive object. MapObject adds the specified object to the internal data structures maintained by the CArchive object during serialization and deserialization, but unlike ReadObject and WriteObject, it does not call serialize on the object.

Example

//MyDocument.h
class CMyDocument : public CDocument
{
public:
   DECLARE_SERIAL(CMyDocument)

   CObList m_listOfSubItems;

   virtual void Serialize(CArchive& ar);
};
//MyDocument.cpp
IMPLEMENT_SERIAL(CMyDocument, CDocument, 1)

void CMyDocument::Serialize(CArchive& ar)
{
   CDocument::Serialize(ar);

   if (ar.IsStoring())
   {
      // TODO: add storing code here
   }
   else
   {
      // TODO: add loading code here
   }

   ar.MapObject(this);  

   //serialize the subitems in the document;
   //they will be able to serialize their m_pDoc
   //back pointer
   m_listOfSubItems.Serialize(ar);
}
//SubItem.h
class CSubItem : public CObject
{
   DECLARE_SERIAL(CSubItem)
   CSubItem() : m_i(0) {};

public:
   CSubItem(CMyDocument * pDoc)
     { m_pDoc = pDoc; }

   // back pointer to owning document
   CMyDocument* m_pDoc; 
   WORD m_i; // other item data

   virtual void Serialize(CArchive& ar);
};
//SubItem.cpp
IMPLEMENT_SERIAL(CSubItem, CObject, 1);

void CSubItem::Serialize(CArchive& ar)

{
   if (ar.IsStoring())
   {
      // will serialize a reference 
      // to the "mapped" document pointer
      ar << (CObject *)m_pDoc;
      ar << m_i;
   }
   else
   {
      // Will load a reference to
      // the "mapped" document pointer
      ar >> (CObject *&) m_pDoc;
      ar >> m_i;
   }
}

Requirements

Header: afx.h

See Also

Concepts

CArchive Class

CArchive Members

Hierarchy Chart

CArchive::ReadObject

CArchive::WriteObject