In many applications, we need to save or read data from the media, which involves file operations. We can use various file access methods to do this,MFC also provides a simple method for reading and writing files-"serialization ". The serialization mechanism provides developers with file control methods that are more convenient to use and transparent to byte streams through higher interface functions, for example, you can write a string to a file without worrying about the specific length. You can even operate on string arrays. With the support of classes provided by MFC that can automatically allocate memory, you can read/write data more easily. You can also compile your own class with serialization function as needed.
Serialization should be supported by classes to be serialized at the lowest level. That is to say, if you need to serialize a class, this class must support serialization. When reading and writing files through serialization, you only need the serialization function of this class.
How can classes be serialized? You need to do the following:
- This class fromCObject is derived.
- IncludeDECLARE_SERIAL macro definition.
- Provides a default constructor.
- Implement in classSerialze Function
- UseIMPLEMENT_SERIAL indicates the class name and version number
The following code creates a simple ID card record class and supports serialization.
In H
Struct strPID
{
Char szName [10];
Char szID [16];
Struct strPID * pNext;
};
Class CAllPID: public CObject
{
Public:
DECLARE_SERIAL (CAllPID)
CAllPID ();
~ CAllPID ();
Public: // serialization related
Struct strPID * pHead;
// Other member functions
Void Serialize (CArchive & ar );
};
In CPP