C ++:如何序列化/反序列化对象没有任何库? [英] C++: how serialize/deserialize objects without any library?
问题描述
我试着理解序列化/反序列化在c ++中如何工作,所以我想做没有任何lib。但我真的坚持。我从简单的对象开始,但当我尝试解冻一个向量我明白,我不能得到一个向量,如果我不写它的大小之前。此外,我不知道应该选择哪种格式的文件,因为如果数字将存在于矢量大小之前我没有机会读它正确。但是它只是向量,但我也想做类和地图容器。我的任务是序列化/反序列化一个对象,如下:
I try to understand how serializing/deserializing works in c++, so I want to do that without any libs. But I really stuck with that. I start with simple objects but when I try to deserilize a vector I understand that I can't get a vector without if I don't write it size before. Moreover, I don't know which format of file I should choose because if digits will be existed before size of vector I haven't chance to read it right. However it is only the vector but I also want to do that with classes and map container. My task is serialize/deserialize a objects as 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 in way as 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;
}
你能建议我如何做这个conplex对象或好
Could you please suggest how I can do this for this conplex object or a good tutorial that explain 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;
};
然后,您要为要序列化的类/ struct实现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 vs big-endian)
- 您的程序如何自动检测,反序列化时创建哪个类。
Clues:
- 使用具有编写bool,int,float, / li>
- 使用字符串表示正在序列化的对象类型,并在反序列化时使用factory创建该对象的实例。
- 使用预定义的宏来确定
这篇关于C ++:如何序列化/反序列化对象没有任何库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!