使用提升序列化多态类
Serializing polymorphic class using boost
当我尝试对 Sphere 是几何子类的数据进行服务器化时,程序崩溃并出现未处理的异常。
在序列化.exe 0x000007FEFCA0B87D引发异常:Microsoft C++异常:在内存位置0x000000000022F730 提升::存档::archive_exception
这发生在"ar&g;"这一行上。
include "pch.h"
#include <iostream>
#include<fstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include "Geometry.h"
#include "Sphere.h"
#include <boost/serialization/export.hpp>
int main()
{
const char* fileName = "saved.txt";
Sphere Sph;
Geometry* g = &Sph;
// save data
{
// Create an output archive
std::ofstream ofs(fileName);
boost::archive::text_oarchive ar(ofs);
ar & g ; // This lines throws exception.
}
Geometry* c_Restored;
//load data
{
// create an input stream
std::ifstream ifs(fileName);
boost::archive::text_iarchive ar(ifs);
ar & c_Restored;
}
c_Restored->PrintGeom();
do
{
std::cout << 'n' << "Press a key to continue...";
} while (std::cin.get() != 'n');
}
///
#include "Geometry.h"
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/export.hpp>
class Sphere : public Geometry
{
private:
std::string stdstrSphere;
public:
Sphere() : stdstrSphere( "DefaultSphere"){}
Sphere( std::string str) : stdstrSphere(str) {}
void PrintGeom()
{
std::cout << "Sphere Virtual Function" << std::endl;
}
private:
typedef Geometry _Super;
friend class boost::serialization::access;
template <typename Archive>
void save(Archive& ar, const unsigned version) const {
boost::serialization::base_object<_Super>(*this);
ar & stdstrSphere;
}
template <typename Archive>
void load(Archive& ar, const unsigned version) {
boost::serialization::base_object<_Super>(*this);
ar & stdstrSphere;
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
/// #pragma 一次
#include <string>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/base_object.hpp>
class Geometry
{
private:
std::string stdstringGeom;
public:
virtual void PrintGeom()
{
std::cout << "geometry virtual function";
}
private:
friend class boost::serialization::access;
template <typename Archive>
void save(Archive& ar, const unsigned version) const {
ar & stdstringGeom;
}
template <typename Archive>
void load(Archive& ar, const unsigned version) {
ar & stdstringGeom;
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
当我编译并运行显示的代码时,异常文本是...
unregistered class - derived class not registered or exported
因此,根本问题是您需要注册派生类,如此处所述。 尝试在main
之前添加以下内容...
BOOST_CLASS_EXPORT_GUID(Sphere, "Sphere")
相关文章:
- C++boost序列化多态性问题
- 序列化多晶型接口
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- 无法初始化已知大小的矢量指针,该大小不会因多态性而更改
- C++ 多态模板类,模板类型对象的实例化
- 从一个文件中读取多个序列化对象
- 是具有接口专用化的子类多态的模板实例化
- 在C++中使用POCO和grain对多个对象进行反序列化
- 结构化绑定语法是否可以在多态 lambda 中使用
- 了解C++中多态对象的序列化
- 使用提升序列化多态类
- 具有模板和多态性的C 序列化器
- 增强序列化多态性类
- 序列化多态类型的常见混淆
- 序列化多态指针的QVector
- boost序列化-源自多态存档
- 如何对多态继承层次结构执行灵活的序列化
- 使用谷物在库中序列化模板化的多态性类型
- 增强多对象序列化
- 序列化具有特定于环境状态的多态类