당신은 스트림 출력 연산자 (<<
를) 과부하 및 각 필드 (또는 그 반대)
편집 출력 스트림 수 : 여기에 완벽한 예입니다 ...
#include <iostream>
#include <fstream>
#include <map>
using namespace std;
template <typename T>
void serialize(ostream& str, const T& field)
{
str.rdbuf()->sputn(reinterpret_cast<const char*>(&field), sizeof(T));
}
template <typename T>
void deserialize(istream& str, T& field)
{
str.rdbuf()->sgetn(reinterpret_cast<char*>(&field), sizeof(T));
}
class MyGame
{
public:
MyGame() : a(), b() {}
MyGame(int av, int bv) : a(av), b(bv) {}
friend ostream& operator<<(ostream& str, MyGame const& game);
friend istream& operator>>(istream& str, MyGame& game);
int getA() const { return a; }
int getB() const { return b; }
private:
int a;
int b;
};
ostream& operator<<(ostream& str, MyGame const& game)
{
serialize(str, game.a);
serialize(str, game.b);
return str;
}
istream& operator>>(istream& str, MyGame& game)
{
deserialize(str, game.a);
deserialize(str, game.b);
return str;
}
int main(void)
{
{
ofstream fout("test.bin", ios::binary);
MyGame game(10, 11);
fout << game;
}
{
ifstream fin("test.bin", ios::binary);
MyGame game;
fin >> game;
cout << "game.a: " << game.getA() << ", game.b: " << game.getB() << endl;
}
return 0;
}
당신은 이해해야합니다 그러나이 방법의 문제점은 결과 파일이 플랫폼에 따라 달라질 수 있습니다 (예 : 이식 불가능).
출처
2010-11-30 13:34:37
Nim
이것은 실제로 바이너리가 아닙니다.;) – Nim
또한 스트림은 필드를 구분하는 분리 기호 (일반적으로 공백)가 필요합니다.이 예에서는 스트림 출력 작업에 누락되어 있으므로 정수를 읽으려고하면 조작중인 스트림이 단순히 예외를 throw합니다 (예 : 생각 해봐, 내가 잘못 할 수 있기 때문에 시험하지 않았다.) – Nim
이것은 잘라 내지 않을 것이다. 먼저 OP가 요구하는대로 포인터를 모두 직렬화하지 않기 때문에 여기에서 "속임수"를 사용합니다. 또한, 네트워크에서 데이터를 전송하는 것과 관련하여 htonl() 및 ntohl()을 사용하여 수행되는 작업과 같은 원시 연산자의 직렬화를 훨씬 강력하게 제어 할 수있는 경우에는 << and >> 연산자가 트릭을 수행한다고 가정합니다. . – Jon