“每当我们在指针(或引用)上调用序列化时,都会在必要时触发其指向(或引用)的对象的序列化”-codeproject.com上的A practical guide to C++ serialization本文提供了一个很好的解释,以演示如何序列化指针序列化指针所指向的数据,因此我编写了一个代码来尝试:
#include <fstream>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class datta {
public:
int integers;
float decimals;
datta(){}
~datta(){}
datta(int a, float b) {
integers=a;
decimals=b;
}
void disp_datta() {
std::cout<<"\n int: "<<integers<<" float" <<decimals<<std::endl;
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & integers;
ar & decimals;
}
};
int main() {
datta first(20,12.56);
datta get;
datta* point_first;
datta* point_get;
point_first=&first;
first.disp_datta();
std::cout<<"\n ptr to first :"<<point_first;
//Serialize
std::ofstream abc("file.txt");
{
boost::archive::text_oarchive def(abc);
abc << point_first;
}
return 0;
}
运行此代码后,我打开file.txt并找到一个十六进制指针地址,而不是该地址所指向的值,我也编写了反序列化代码:
std::ifstream zxc("file.txt");
{
boost::archive::text_iarchive ngh(zxc);
ngh >> point_get;
}
//Dereference the ptr and
get = *point_get;
get.disp_datta();
std::cout<<"\n ptr to first :"<<point_get;
我在这里有细分错误!谁能告诉我如何使它工作?非常感谢!
最佳答案
您将对象写入流中,而不是存档中:)
boost::archive::text_oarchive def(abc);
abc << point_first;
尝试
def << point_first;
代替。结果:
22 serialization::archive 10 0 1 0
0 20 12.56
看到它 Live (with deserialization) On Coliru