0

我想将父类中的对象保存在文本文件中,然后能够加载对象。问题是所有对象都是指针,因此只能保存对象的地址,而不能保存对象本身。下面的代码可以编译,但我不确定 .txt 文件中信息的含义是什么。

#include <iostream>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <sstream>

class Gear {
  public:
    template<typename Archive>
    void serialize(Archive& ar, unsigned int version) { ar & v; }

    void setV (const double& _v) { v = _v; }
    double getV () { return v; }

    void status () { std::cout << "v = " << v << std::endl; }

  private:
    double v;
};

class Car {
  public:
    template<typename Archive>
    void serialize(Archive& ar, unsigned int version) {
      ar & hp;
      ar & x;
    }
    void setHP (const int& _hp) { hp = _hp; }
    void setGear (Gear* _Gear) { x = _Gear; }
    void status () { std::cout << "hp = " << hp << " Gear with v = " << x->getV() << std::endl; }

  private:
    int hp;
    Gear *x;
};

int main() {
  // Define new Gear:
  Gear* g = new Gear();
  g->setV(2.5);
  g->status();

  // Expectation is Car sets up the Gear.
  Car c;
  c.setHP(80);
  c.setGear(g);
  c.status();




  std::ofstream outputStream;
  outputStream.open("Car.txt");
  boost::archive::text_oarchive outputArchive(outputStream);
  outputArchive << c;
  outputStream.close();

  Car b;
  std::ifstream inputStream;
  inputStream.open("Car.txt", std::ifstream::in);
  boost::archive::text_iarchive inputArchive(inputStream);
  inputArchive >> b;
  b.status();
  inputStream.close();
  return 0;


}

在我得到的文件中:

22 serialization::archive 10 0 0 80 1 1 0
0 2.5

这一切意味着什么?2.5 是有道理的,但其他我不确定。

我还使用了 sstream 而不是 io/fstream(将代码从 std::ofstream outputStream; 替换为 inputStream.close(); 代码如下):

    std::stringstream ss;
    boost::archive::text_oarchive oa{ss};
    oa << c;

    Car b;
    boost::archive::text_iarchive ia{ss};
    ia >> b;
    b.status();

使用此代码,我得到(在使用命令 g++ -std=c++11 boost_serial.cpp -lboost_serialization 运行 ./a.out 之后):

v = 2.5
hp = 80 Gear with v = 2.5
hp = 80 Gear with v = 2.5
4

0 回答 0