序列化C ++对象 [英] Serializing C++ objects

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

问题描述

我想实现一个序列化类,它接收一个对象,并将其转换为二进制流并存储在文件中。后来,应该从一个文件重建对象。

I would like to implement a Serialization Class which takes in an object and converts it into a binary stream and stored in a file. Later, the object should be reconstructed from a file.

虽然这个功能是由BinaryFormatter在C#提供的,我想设计我的
自己的序列化类

Though this functionality is provided by BinaryFormatter in C#, I would like to design my own Serialization class from scratch.

有人可以指向某些资源吗?

Can someone point to some resources ?

提前感谢

推荐答案

我一直使用boost :: serialization库一段时间,我认为这是非常好的。你只需要创建这样的序列化代码:

I have been using boost::serialization library for a while now and I think it is very good. You just need to create the serialization code like this:

class X {
  private:
    std::string value_;
  public:
    template void serialize(Archive &ar, const unsigned int version) {
       ar & value_;
     };
 }

无需创建反序列化代码(这就是为什么他们使用& amp ;运算符)。但如果你喜欢你仍然可以使用<<和>>运算符。

No need to create the de-serialization code ( that's why they used the & operator ). But if you prefer you can still use the << and >> operators.

也可以为没有修改的类编写序列化方法(例如:如果需要序列化来自库的对象)。在这种情况下,您应该做类似的操作:

Also it's possible to write the serialization method for a class with no modification ( ex.: if you need to serialize an object that comes from a library ). In this case, you should do something like:

namespace boost { namespace serialization {
       template
       void serialize(Archive &ar, X &x const unsigned int version) {
                    ar & x.getValue();
       };
    }}

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

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