C++ MFC Serialization

与世无争的帅哥 提交于 2020-01-25 21:05:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!