我正在尝试序列化我的数据结构,以便将它们写入 tcp 套接字。
到目前为止,我发现我的问题是序列化。我什至尝试使用
BOOST_SERIALIZATION_ASSUME_ABSTRACT(T)
但我找不到任何类似于我的程序的工作示例以及如何正确实现它。
以下是我访问过的一些链接:
- http://programmers-blog.com/category/cc
- http://www.boost.org/doc/libs/1_48_0/libs/serialization/doc/tutorial.html#simplecase
- http://en.highscore.de/cpp/boost/serialization.html#serialization_class_hierarchies
我的数据结构比这个复杂一点,但我们假设我有以下结构
坐标.h
#include <boost\archive\text_iarchive.hpp>
#include <boost\archive\text_oarchive.hpp>
class Coordinate {
public:
Coordinate() {}
Coordinate(int c) : c(c) {}
int get(void) { return c; }
std::string toString(void);
private:
int c;
friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & this->c;
}
};
移动.h
class Coordinate;
#include "Coordinate.h"
#include <boost\archive\text_iarchive.hpp>
#include <boost\archive\text_oarchive.hpp>
class Move {
public:
Move() {}
~Move() {}
Coordinate* getCoordinate(void) {return this->destination; }
virtual bool isJump(void) = 0;
protected:
Coordinate *destination;
private:
friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & this->destination;
}
};
移动正常.h
class Coordinate;
#include "Move.h"
#include "Coordinate.h"
#include <boost\archive\text_iarchive.hpp>
#include <boost\archive\text_oarchive.hpp>
class MoveNormal : public Move {
public:
MoveNormal() {}
MoveNormal(Coordinate *destination) { this->destination = destination; }
~MoveNormal() {}
virtual bool isJump(void);
private:
friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & boost::serialization::base_object<Move>(*this);
}
};
虚拟方法在这里定义。
移动正常.cpp
#include "MoveNormal.h"
bool MoveNormal::isJump(void) {
return false;
}
我的 main.cpp 看起来像这样:
#include "Coordinate.h"
#include "Move.h"
#include "MoveNormal.h"
#include <fstream>
#include <boost\archive\text_iarchive.hpp>
#include <boost\archive\text_oarchive.hpp>
int main(int argc, char *argv[]) {
Coordinate *c = new Coordinate(10);
// This runs OK
/*
{
std::ofstream ofs("f.txt");
boost::archive::text_oarchive oa(ofs);
oa << c;
}
Coordinate *d;
{
std::ifstream ifs("f.txt");
boost::archive::text_iarchive ia(ifs);
ia >> d;
}
std::cout << "c.get(): " << c->get() << std::endl;
std::cout << "d.get(): " << d->get() << std::endl;
*/
// This is where I get my error
Move *m = new MoveNormal(c);
{
std::ofstream ofs("f.txt");
boost::archive::text_oarchive oa(ofs);
oa << m; // Line where the error occurs
}
return 0;
}
但是当我运行程序时,出现以下错误:
Test.exe 中 0x76dbb9bc 处未处理的异常:Microsoft C++ 异常:内存位置 0x001df078 处的 boost::archive::archive_exception..
我正在使用 VS2010 和 Boost 1.48.0。