Specifying Levels of Functionality
This article describes how to add the following levels of functionality to your CObject-derived class:
Run-time class information
Dynamic creation support
Serialization support
For a general description of CObject functionality, see the article Deriving a Class from CObject.
To add run-time class information
Derive your class from CObject, as described in the Deriving a Class from CObject article.
Use the DECLARE_DYNAMIC macro in your class declaration, as shown here:
class CPerson : public CObject { DECLARE_DYNAMIC( CPerson ) // other declarations };
Use the IMPLEMENT_DYNAMIC macro in the implementation file (.CPP) of your class. This macro takes as arguments the name of the class and its base class, as follows:
IMPLEMENT_DYNAMIC( CPerson, CObject )
注意
Always put IMPLEMENT_DYNAMIC in the implementation file (.CPP) for your class. The IMPLEMENT_DYNAMIC macro should be evaluated only once during a compilation and therefore should not be used in an interface file (.H) that could potentially be included in more than one file.
To add dynamic creation support
Derive your class from CObject.
Use the DECLARE_DYNCREATE macro in the class declaration.
Define a constructor with no arguments (a default constructor).
Use the IMPLEMENT_DYNCREATE macro in the class implementation file.
To add serialization support
Derive your class from CObject.
Override the Serialize member function.
注意
If you call Serialize directly, that is, you do not want to serialize the object through a polymorphic pointer, omit steps 3 through 5.
Use the DECLARE_SERIAL macro in the class declaration.
Define a constructor with no arguments (a default constructor).
Use the IMPLEMENT_SERIAL macro in the class implementation file.
注意
A "polymorphic pointer" points to an object of a class (call it A) or to an object of any class derived from A (say, B). To serialize through a polymorphic pointer, the framework must determine the run-time class of the object it is serializing (B), since it might be an object of any class derived from some base class (A).
For more details on how to enable serialization when you derive your class from CObject, see the articles Files in MFC and Serialization.