C ++ MFC序列化 [英] C++ MFC Serialization

查看:77
本文介绍了C ++ MFC序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要序列化指向基类和派生类的指针的向量. 这两个类都重载了序列化函数,所以我成功地做到了:`

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();

问题是,现在应该如何对它进行反序列化?我不知道在从CArchive读取对象时调用正确的构造方法...

So the question is, how should I DEserialize it now? I have no ideas about calling correct constructor while reading objects from CArchive...

推荐答案

您首先需要保存容器中元素的数量(使用ar.WriteCount).然后(由于容器中包含多种类型),您序列化的每个元素都需要包括额外的数据以告诉您该元素的类型是什么.这可能只是一个额外的字符(0 =基类,1 =第一个派生类),另一个计数类型编号(用WriteCount编写),或者更复杂的类型名称.

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.

要读回它,您要读取元素计数(使用ar.ReadCount),然后对于要读入的每个元素,您都要读取类型字符,计数或其他内容,分配该类型的新元素,反序列化为新的已分配元素,最后将已分配元素存储在您要反序列化的容器中.

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.

为了从MFC容器转换为STL容器,我需要做很多年前的事情,而MFC容器(在<afxtempl.h>中)使用的Serialize的实现非常有帮助.

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.

这篇关于C ++ MFC序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆