Boost的对象序列化错误

时间:2017-02-26 19:56:39

标签: c++ serialization boost

我正在尝试存储User对象,然后使用boost serialization library和VS2015社区读取存储的对象。我按照教程here进行了操作。目前文件的读/写对象工作得很好;然而,在读回对象后,我无法访问任何对象成员(即用户名和pw_hash)。有什么我想念的吗?我已经看到了很多关于如何使用库来编写/读取对象的问题,但是没有任何问题显示在从文件中读取对象后访问对象成员的任何人。

类别:

#ifndef USER_H
#define USER_H

#include <fstream>
#include <string>
#include <boost\serialization\string.hpp>
#include <boost\archive\text_oarchive.hpp>
#include <boost\archive\text_iarchive.hpp>

#include "Hash.h"

class User
{
   public:
      User();
      User(std::string & name, std::string & pwd);
      ~User();

   private:
      std::string pw_hash;
      std::string username;

      inline std::string get_username();
      inline void set_username(const std::string & name);
      inline std::string get_PwHash();
      inline void set_PwHash(const std::string & hash);

      friend class boost::serialization::access;
      template<class Archive>
      void serialize(Archive & ar, const unsigned int version)
      {
         ar & username;
         ar & pw_hash;
      }
};
#endif

以下是我遇到问题的地方。从内存中读取对象后,VS2015强调test2.get_username()表示无法访问该对象。

实现:

#include "User.h"
int main(int argc, char *argv[])
{
   User test("User1", "Password");
   std::cout << test.get_username() << std::endl;
   {
      std::ofstream ofs("User1");
      boost::archive::text_oarchive oa(ofs);
      oa << test;
   }

   User test2();
   {
      std::ifstream ifs(username);
      boost::archive::text_iarchive ia(ifs);
      ia >> test2;
      //error
      std::cout << test2.get_username() << std::endl;
   }
   return 0;
}

0 个答案:

没有答案