C ++:如何在不使用库的情况下序列化/反序列化对象? [英] C++: how to serialize/deserialize objects without the use of libraries?
问题描述
我试图了解在不使用库的情况下C ++中的序列化/反序列化如何工作。我从简单的对象开始,但是当对向量进行反序列化时,我发现,如果不先编写向量的大小就无法获得向量。而且,我不知道应该选择哪种文件格式,因为如果数字在矢量大小之前存在,我将无法正确阅读。此外,我想使用类和映射容器来做到这一点。我的任务是像这样对对象进行序列化/反序列化:
I am trying to understand how serialization/deserialization works in C++ without the use of libraries. I started with simple objects but when deserializing a vector, I found out, that I can't get the vector without having written its size first. Moreover, I don't know which file format I should choose, because, if digits exist before vector's size I can't read it right. Furthermore, I want to do that with classes and map containers. My task is to serialize/deserialize an object like this:
PersonInfo
{
unsigned int age_;
string name_;
enum { undef, man, woman } sex_;
}
Person : PersonInfo
{
vector<Person> children_;
map<string, PersonInfo> addrBook_;
}
当前,我知道如何序列化这样的简单对象:
Currently I know how to serialize simple objects like this:
vector<PersonInfo> vecPersonInfo;
vecPersonInfo.push_back(*personInfo);
vecPersonInfo.push_back(*oneMorePersonInfo);
ofstream file("file", ios::out | ios::binary);
if (!file) {
cout<<"can not open file";
} else {
vector<PersonInfo>::const_iterator iterator = vecPersonInfo.begin();
for (; iterator != vecPersonInfo.end(); iterator++) {
file<<*iterator;
}
请问我该如何为这个复杂的对象或
Could you please suggest, how can I do this for this complex object or a good tutorial that explains it clearly?
推荐答案
一种模式是实现抽象类,该抽象类定义用于序列化的函数,并且该类定义什么进入序列化器,结果如何。例如:
One pattern is to implement an abstract class the defines functions for serialization and the class defines what goes into the serializer and what comes out. An example would be:
class Serializable
{
public:
Serializable(){}
virtual ~Serializable(){}
virtual void serialize(std::ostream& stream) = 0;
virtual void deserialize(std::istream& stream) = 0;
};
然后为要序列化的类/结构实现Serializable接口:
You then implement Serializable interface for the class/struct that you want to serialize:
struct PersonInfo : public Serializable // Yes! It's possible
{
unsigned int age_;
string name_;
enum { undef, man, woman } sex_;
virtual void serialize(std::ostream& stream)
{
// Serialization code
stream << age_ << name_ << sex_;
}
virtual void deserialize(std::istream& stream)
{
// Deserialization code
stream >> age_ >> name_ >> sex_;
}
};
我相信你知道。以下是一些可以克服的障碍,您可以在闲暇时做:
Rest I believe you know. Here's a few hurdles to pass though and can be done in your leisure:
- 当您在流中写入一个带有空格的字符串时,尝试读回去,您只会得到其中的一部分,而字符串的其余部分会破坏此后读取的值。
- 如何对其进行编程以使其跨平台(little-endian与big-endian)
- 程序反序列化时如何自动检测要创建的类。
线索:
- 使用具有写bool,int,float,string等功能的自定义序列化器。 / li>
- 使用字符串表示要序列化的对象类型,并在反序列化时使用工厂创建该对象的实例。
- 使用预定义的宏来确定哪个
- 总是在固定字节序中写入文件,并使使用其他字节序的平台适应该格式。
这篇关于C ++:如何在不使用库的情况下序列化/反序列化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!