序列化究竟如何在C ++中运行?

时间:2013-11-08 11:07:57

标签: c++ serialization file-io

以下是我的代码文件:

的main.cpp

#include <iostream>
#include <fstream>
#include "Car.h"
#include "Engine.h"
using namespace std;

int main() {
   Car* car = new Car(1984);
   /* do something here */
   delete car;   
   return 0;
}

Car.h

#ifndef CAR_H
#define CAR_H

#include <iostream>
using namespace std;

#include "Engine.h"

class Car {
public:
   Car(int);
   virtual ~Car();
   void serialize(ostream& s) {
      engine.serialize(s);
      s << ' ' << yearModel;
   } 
   void unserialize(istream& s) {
      engine.unserialize(s);
      s >> yearModel;
   }
private:
   Engine engine;
   int yearModel;
};

#endif /* CAR_H */

Car.cpp

#include "Car.h"

Car::Car(int year) {
   yearModel = year;
}

Car::~Car() {
}

Engine.h

#ifndef ENGINE_H
#define ENGINE_H

#include <iostream>
using namespace std;

class Engine {
public:
   Engine();
   virtual ~Engine();
   void serialize(ostream& s) {
      s << ' ' << engineType;
   } 
   void unserialize(istream& s) {
      s >> engineType;
   }
private:
   int engineType;
};

#endif /* ENGINE_H */

Engine.cpp

#include "Engine.h"

Engine::Engine() {
   engineType = 1;
}

Engine::~Engine() {
}

我想在main.cpp中做的是将创建的Car对象保存到file.txt,然后从那里读取它。这究竟是如何工作的?例如:如何在Car类中调用序列化函数?

如果我听起来像菜鸟,我很抱歉,但这整个序列化对我来说都是新鲜事。

编辑:当我在所有序列化和非序列化函数前添加'void'时,代码现在编译。

1 个答案:

答案 0 :(得分:3)

这与序列化无关:函数需要返回类型,即使它是void。所以这是错误的:

serialize(ostream& s) // look, no return type.

您可能需要返回void

void serialize(ostream& s) { /* code as before */ }

或通过引用返回流以允许链接:

ostream& serialize(ostream& s) {
  return s << ' ' << engineType;
}