How does VC ++ MFC generate a serializable class, vcmfc
1. MFC allows the persistent serialization mechanism of objects throughout the program running
(1) serialization refers to the process of reading or writing objects to persistent storage media (such as a disk file.
(2) serialization is used to fix the status of structured data (such as C ++ classes or structures) during or after the program runs.
(3) MFC supports serialization in the CObject class. Therefore, all classes inherited from CObject can use the serialization protocol of CObject.
(4) The basic idea of serialization:
A. An object must be able to write its current state to a persistent storage medium, which is usually implemented using its member variables.
B. objects can be read or deserialized to reconstruct the object state from the storage media.
C. serialize the details of all object pointers and the circular references to objects when serializing objects.
D. The key point is that the object itself is responsible for reading and writing its own State. Therefore, when serializing an object, it must be a basic serialization operation.
(5) MFC uses the CArchive class object as the intermediate medium between the serialized object and the storage medium.
2. Generate a serializable class
(1) Derive your class from CObject. (defines a class whose base class is CObject)
(2) Override the Serialize member function. (rewrite the serialized function)
(3) Use the DECLARE_SERIAL macro in the class declaration. (Use the DECLARE_SERIAL macro in the class declaration file)
(4) Define a constructor with no arguments (a default constructor). (Define a constructor without parameters)
(5) Use the IMPLEMENT_SERIAL macro in the class implementation file. (Use the IMPLEMENT_SERIAL macro in the implementation file)
Iii. Instances
Graph. h file:
# Pragma once // Graph Command target class Graph: public CObject // (1) define a class whose base class is COject {DECLARE_SERIAL (Graph) // (3) use the DECLARE_SERIAL macro public: Graph (); // (4) in the class declaration file to define a non-parameter constructor Graph (int drawType, CPoint ptOld); virtual ~ Graph (); void Serialize (CArchive & ar); // (2) rewrite the serialization function private: int m_drawType; CPoint m_ptOld ;};Graph. cpp file:
// Graph. cpp: implementation file
//
# Include "stdafx. h"
# Include "Archive. h"
# Include "Graph. h"
// Graph
IMPLEMENT_SERIAL (Graph, CObject, 1) // (5) use the IMPLEMENT_SERIAL macro in the implementation file
Graph: Graph () // (4) defines a constructor without parameters.
{
}
Graph: Graph (int drawType, CPoint ptOld)
{
This-> m_drawType = drawType;
This-> m_ptOld = ptOld;
}
Graph ::~ Graph ()
{
}
// Graph member functions
Void Graph: Serialize (CArchive & ar) // (2) rewrite the serialization Function
{
If (ar. IsStoring ())
{
Ar <m_drawType <m_ptOld;
}
Else
{
Ar> m_drawType> m_ptOld;
}
}
After that, you can implement serialize classes.