问题
I need to serialize a vector of pointers to base class and derived class. Serialize function overloaded for both classes, so I did it succesfully like this:`
CFile out;
if (!out.Open(filename.c_str(), CFile::modeWrite | CFile::modeCreate))
return false;
CArchive ar(&out, CArchive::store);
for (auto it = container_.begin(); it != container_.end(); ++it)
{
(*it)->Serialize(ar);
}
ar.Close();
out.Close();
So the question is, how should I DEserialize it now? I have no ideas about calling correct constructor while reading objects from CArchive...
回答1:
You'll first need to save out the count of elements in the container (using ar.WriteCount
). Then (since your container has multiple types in it) for each element you serialize you'll need to include extra data to tell you what the type of that element is. This could be just one extra character (0 = base class, 1 = first derived class), another count type number (written with WriteCount), or something more elaborate like type names.
To read it back in you read the element count (using ar.ReadCount
), then for each element to read in you read the type character, count, or whatever, allocate a new element of that type, deserialize into the newly allocated element, and finally store the allocated element into the container you are deserializing.
I needed to do something similar many years ago in order to transition from MFC containers to STL ones, and the implementation of Serialize used by the MFC containers (in <afxtempl.h>
) was very helpful.
来源:https://stackoverflow.com/questions/33703914/c-mfc-serialization