Essential conditions for serializable[Transferred from "getting down to MFC", Hou Junjie]
To make an object capable of serialize, it must be derived from a serializable class. If a class is intended to become serializable, the following five conditions must be met. As for the reasons, all the above discussions have been explained.
1. Derived from cobject. In this way, the rtti, dynamiccreation, and other functions can be guaranteed.
2. The declare_serial macro must be included in the declaration part of the class. This macro requires a parameter: Class Name.
3. The implement_serial macro must be included in the implementation part of the class. This macro requires three parameters: Class Name and schema No ..
4. Rewrite the serialize virtual function so that it can properly write the class member variables into the file.
5. Add a default constructor to the class (that is, the constructor without parameters ). This condition is often ignored, but it is necessary because if an object comes from a file, MFC must first create it dynamically and call its constructor without any parameters, then, the object data is read from the file.
So, let's review the cstroke in this example to see if the above five conditions are met:
// In scribbledoc. H class cstroke: Public cobject // derived from cobject (condition 1) {public: cstroke (uint npenwidth); protected: cstroke (); // has a default constructor (condition 5) declare_serial (cstroke) // use the serial macro (condition 2) protected: uintm_npenwidth; public: carray <cpoint, cpoint> m_pointarray; public: Virtual void serialize (carchive & AR ); // rewrite the serialize function (Condition 4)}; // In scribbledoc. CPP implement_serial (cstroke, cobject, 1) // use the serial macro (Condition 3) cstroke: cstroke () // have a default constructor (condition 5) {// This empty constructor shocould be used by serialization only} void cstroke: serialize (carchive & AR) // rewrite the serialize function (Condition 4) {cobject :: serialize (AR); // The manual tells us that we 'd better call this function first. // It is an empty function in the current MFC version, so it doesn't matter if (AR. isstoring () {ar <(Word) m_npenwidth; m_pointarray.serialize (AR) ;}else {word w; Ar >>w; m_npenwidth = W; m_pointarray.serialze (AR );}}