【问题标题】:Deserialize class instance in C++在 C++ 中反序列化类实例
【发布时间】:2016-02-09 11:38:25
【问题描述】:

这是我的 *.h

class ip_file_handler {

   struct IPheader {
      unsigned short int ver :4;
      unsigned short int ihl :4;
      unsigned short int total_length;
      unsigned char tos;
      unsigned char ttl;
      unsigned char protocol;
      unsigned int checksum;
      unsigned short int identification;
      unsigned short int flag_offset;
      unsigned int ucSource;
      unsigned int ucDestination;
   };

   public:

   ip_file_handler(){}

   // func 1 (file to ip)
   static bool file_to_ip_packets(std::string input_file_name,
                                  std::string output_file_name,
                                  unsigned int source_ip,
                                  unsigned int destination_ip);

   private:

   IPheader ipInfo;
   list<string> data;
};

在 *.cpp 中:

文件的所有数据到myHandler中。

这一行将类写入文件:

ofstream outFile(output_file_name.c_str(), ios::out | ios::binary);
ip_file_handler myHandler;
outFile.write((char*) &myHandler,sizeof(ip_file_handler));

/* 这里有问题 */ 这一行从文件中读取类:

ip_file_handler tmp;
outFile2.read((char*) &tmp, sizeof(ip_file_handler));

现在为什么不能从文件中读取类!? outFile 不是空的!

谢谢大家。 亚当

【问题讨论】:

  • 一般来说,将对象二进制转储到文件并将其二进制转储回内存是不安全的。您需要添加函数(或流运算符)来手动写入/读取每个成员。
  • 正确格式化您的问题并使用正确的拼写和语法。如果你不为你的问题付出任何努力,就不要指望陌生人关心你的问题。

标签: c++ serialization


【解决方案1】:

列表的数据(嗯,data)没有存储在你的类中,而是在堆上单独分配的。当您只转储ip_file_handler 的副本时,它不会存储在文件中。

您必须分别写出列表中的每个字符串,并在再次读回它们时重新创建列表。

【讨论】:

  • 谢谢 Bo Persson,我会试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
  • 2019-06-25
相关资源
最近更新 更多