我有一个类A
,其中包含类B
的对象,我想对其进行序列化。问题是,类C
继承自B
,因此A
可以包含B
或C
的对象。如何使用Boost有效地实现序列化?
下面是我的尝试,但是尝试使用A
对象序列化C
时出现错误,而使用B
进行序列化则可以正常工作。你知道吗,我在做什么错了?
我已经找到了有关类层次结构对象序列化here的一些信息,但是它需要在text_iarchive
中显式注册该类型,而我需要将其注册在{{1}中}类,因为我没有直接序列化A
对象。
B
#include <fstream>
#include <iostream>
#include <vector>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class B {
friend class boost::serialization::access;
private:
template<class Archive>
void save(Archive & ar, const unsigned int version) const {
ar & this->v->size();
for(int i = 0; i < this->v->size(); i++) {
ar & (*(this->v))[i];
}
};
template<class Archive>
void load(Archive & ar, const unsigned int version) {
size_t size;
int tmp;
ar & size;
this->v = new std::vector<int>(size);
for(int i = 0; i < size; i++) {
ar & tmp;
(*this->v)[i] = tmp;
}
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
protected:
std::vector<int>* v;
public:
B();
B(std::vector<int>* v);
virtual void print_vals();
};
B::B() {
this->v = nullptr;
}
B::B(std::vector<int>* v) {
this->v = v;
}
void B::print_vals() {
for(auto e : *(this->v)) {
std::cout << e << std::endl;
}
}
class C : public B {
friend class boost::serialization::access;
private:
int num2;
template<class Archive>
void serialize(Archive & ar, const unsigned int version){
ar & boost::serialization::base_object<B>(*this);
ar & num2;
};
public:
void print_vals() override {
for(auto e : *(this->v)) {
std::cout << e << std::endl;
}
std::cout << this->num2 << std::endl;
}
C();
C(int num2, std::vector<int>* v);
};
C::C() {
this->num2 = -1;
this->v = nullptr;
}
C::C(int num2, std::vector<int> *v) {
this->num2 = num2;
this->v = v;
}
class A {
friend class boost::serialization::access;
private:
int num;
B* b_obj;
template<class Archive>
void serialize(Archive & ar, const unsigned int version){
ar & num;
ar & b_obj;
};
public:
A();
A(int num, B* b);
void print_vals();
};
A::A() {
this->num = -1;
this->b_obj = nullptr;
}
A::A(int num, B* b) {
this->num = num;
this->b_obj = b;
}
void A::print_vals() {
std::cout << this->num << std::endl;
this->b_obj->print_vals();
}
int main() {
std::vector<int> v{1,2,3};
B b = B(&v);
A a(4, &b);
std::cout << "a:" << std::endl;
a.print_vals();
std::ofstream ofs("a.txt");
{
boost::archive::text_oarchive oa(ofs);
oa << a;
ofs.close();
}
A a2;
std::ifstream ifs("a.txt");
{
boost::archive::text_iarchive ia(ifs);
ia >> a2;
ifs.close();
}
std::cout << "a2:" << std::endl;
a2.print_vals();
C c(2, &v);
A a3(6, &c);
std::cout << "a3:" << std::endl;
a3.print_vals();
std::ofstream ofs2("a3.txt");
{
boost::archive::text_oarchive oa(ofs2);
oa << a3;
ofs.close();
}
A a4;
std::ifstream ifs2("a3.txt");
{
boost::archive::text_iarchive ia(ifs2);
ia >> a4;
ifs.close();
}
std::cout << "a4:" << std::endl;
a4.print_vals();
}
答案 0 :(得分:0)
事实证明您错过了BOOST_CLASS_EXPORT
派生类,即
BOOST_CLASS_EXPORT(C)
没有该宏,Boost序列化将无法正确序列化指向派生对象的指针。
您可以找到完整的工作代码here