使用iostream<<序列化用户对象 [英] Using iostream << to serialize user objects

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

问题描述

我想使用运算符<<"将对象序列化为二进制文件,但是 当我序列化例如int字段时,我获得了它的符号表示形式:

I want serialize object to binary file using operator "<<", but when I serialize, for example, int fields, I obtained it's symbolic representation:

ofstream out("file", ios::out | ios::binary);
int i=0xAA;
out << i;

并输出:

0x31 0x37 0x30

即(0xAA-> 170)

i.e. (0xAA -> 170)

170

如果我使用写功能,一切正常:

If I use write function, all ok:

out.write((char*)&i,sizeof(int));

输出:

0xAA 0x00 0x00 0x00

但是我可以使用<<而不是写函数,序列化对象? 喜欢:

But can I use << instead write function, to serialize object? Like:

out << obj.field1 << obj.field2; // etc.

推荐答案

首先,警告:您确实知道int或类似内容中的字节取决于您的编译器,计算机和操作系统,对吗?对于上面的示例,其他系统可能会输出字节0x00 0x00 0x00 0xAA或完全输出其他内容.这意味着,如果将这些字节发送到另一台计算机并尝试读取它们,则不一定会恢复原来的int.

First, a warning: You do know that the bytes within an int, or anything similar, depends on your compiler, computer, and operating system, right? Other systems might output bytes 0x00 0x00 0x00 0xAA for your example above, or something else entirely. Which means that if you send those bytes to a different computer and attempt to read them, you won't necessarily get your original int back.

无论如何.如果只想吐出整个对象,一种设置方法是通过重载operator<<:

Anyway. If you just want to spit out entire objects, one way to set this up would be to just define serialization for your class(es) and/or struct(s) by overloading operator<<:

std::ostream& operator<<(std::ostream& out, const MyClass& obj) {
  out.write(reinterpret_cast<const char*>(&obj.field1),
            sizeof(obj.field1)); // or something better defined
  // ...
  return out;
}

ofstream out("file", ios::out | ios::binary);
out << obj1 << obj2;

这篇关于使用iostream&lt;&lt;序列化用户对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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