在C ++中序列化和反序列化对象

时间:2017-05-28 13:01:23

标签: mysql c++11 serialization deserialization

我是C ++的新手,我找不到如何用二进制序列化对象的详细示例,这样我就可以将它保存到mysql服务器然后进行反序列化。

该对象如下所示:

class house{
        public:
          int houseNumber;
          bool isEmpty;
          Dweller *dweller;
};
     class Dweller{
       public:
         int phoneNumber;
         bool man;
         Backpack backpack;
};
     class Backpack{
      public:
        int item1;
        int item2;
        int item3;
        int item4;
        float weight;
        bool empty;
};

我必须序列化拥有其他对象的house对象。

1 个答案:

答案 0 :(得分:0)

我能够使用以下方法解决问题:

#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>

请参阅我使用 #include "boost/serialization/vector.hpp" ,因为现在'居民'位于向量中以便于使用

然后代码保持这样:

class house{
    public:
      int houseNumber;
      bool isEmpty;
      std::vector<Dweller> dweller;
    private:
      friend class boost::serialization::access;
      template <class archive>
      void serialize(archive &ar, const unsigned int version)
      {
        ar &houseNumber;
        ar &isEmpty;
        ar &dweller;
      }
};
class Dweller{
    public:
      int phoneNumber;
      bool man;
      Backpack backpack;
    private:
      friend class boost::serialization::access;
      template <class archive>
      void serialize(archive &ar, const unsigned int version)
      {
        ar &phoneNumber;
        ar &man;
        ar &backpack;
      }
};
class Backpack{
    public:
      int item1;
      int item2;
      int item3;
      int item4;
      float weight;
      bool empty;
    private:
      friend class boost::serialization::access;
      template <class archive>
      void serialize(archive &ar, const unsigned int version)
      {
        ar &item1;
        ar &item2;
        ar &item3;
        ar &item4;
        ar &weight;
        ar &empty;
      }
};

所以序列化我用过:

#include <iostream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <sstream>

int main()
{
  Backpack _backpack;
  _backpack.item1 = 0;
  _backpack.item1 = 1;
  _backpack.item1 = 2;
  _backpack.item1 = 3;
  _backpack.item1 = 4;
  _backpack.weight = 3.21;
  _backpack.empty = false;
  Dweller _dweller1;
  _dweller.phoneNumber = 1234567;
  _dweller.man = false;
  _dweller.backpack = _backpack;
  Dweller _dweller2;
  _dweller.phoneNumber = 7654321;
  _dweller.man = true;
  _dweller.backpack = _backpack;

  std::vector<Dweller> _dwellers;
  _dwellers.push_back(_dweller1);
  _dwellers.push_back(_dweller2);
  house _house;
  _house.houseNumber = 4;
  _house.isEmpty = false;
  _house.dweller = _dwellers;

  /*Serializing*/
  std::stringstream ss;
  boost::archive::binary_oarchive oa(ss);
  oa << _house;
  /*Deserializing*/
  boost::archive::binary_iarchive ia(ss);
  house _house2;
  ia >> _house2;
}