在下面的代码段中,我将2个对象存储在' filename'文件,但惊讶地看到在反序列化期间第一次对象值检索2次。除此之外,我想在同一个文件中存储和检索多个类对象。目前我能够将对象存储在文件中但无法检索。
任何人都可以通过这个来解释一下吗?
#include <fstream>
#include <iostream>
// include headers that implement a archive in simple text format
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
using namespace std;
/////////////////////////////////////////////////////////////
// object_model
//
// illustrates serialization for a simple type
//
class object_model
{
private:
friend class boost::serialization::access;
// When the class Archive corresponds to an output archive, the
// & operator is defined similar to <<. Likewise, when the class Archive
// is a type of input archive the & operator is defined similar to >>.
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & classval;
ar & property;
}
string classval;
int property;
public:
object_model(){};
object_model(string d, int p) :
classval(d), property(p)
{}
string getClassval()
{
return classval;
}
int getproperty()
{
return property;
}
};
int main() {
// create and open a character archive for output
std::ofstream ofs("filename");
// create class instance
object_model g("lidar",10);
{
// save data to archive
boost::archive::text_oarchive oa(ofs);
// write class instance to archive
oa << g;
}
object_model g1("lidar1",20);
{
// save data to archive
boost::archive::text_oarchive oa(ofs);
// write class instance to archive
oa << g1;
}
// ... some time later restore the class instance to its orginal state
object_model newg;
{
// create and open an archive for input
std::ifstream ifs("filename");
boost::archive::text_iarchive ia(ifs);
// read class state from archive
ia >> newg;
cout<<newg.getClassval();
cout<<newg.getproperty();
cout<<"done"<<endl;
}
// archive and stream closed when destructors are called
object_model newg1;
{
// create and open an archive for input
std::ifstream ifs("filename");
boost::archive::text_iarchive ia(ifs);
// read class state from archive
ia >> newg1;
cout<<newg1.getClassval();
cout<<newg1.getproperty();
cout<<"done"<<endl;
}
return 0;
}
答案 0 :(得分:1)
将数据保存到存档对象时,您需要完全重定向该对象。对我来说,它非常适用。
object_model g(&#34; lidar&#34;,10); object_model g1(&#34; lidar1&#34;,20);
{ //将数据保存到存档
boost::archive::text_oarchive oa(ofs);
// write class instance to archive
oa << g<<g1;
}
// ...稍后将类实例恢复到原始状态
object_model newg;
object_model newg1;
{
// create and open an archive for input
std::ifstream ifs("filename");
boost::archive::text_iarchive ia(ifs);
// read class state from archive
ia >> newg>>newg1;
cout<<newg.getClassval();
cout<<newg.getproperty();
cout<<newg1.getClassval();
cout<<newg1.getproperty();
cout<<"done"<<endl;
}