我正在查看组织论文的代码。我有两个通过包含和指针互连的类(作者和论文)。我为这两个类定义了序列化,但是如果我丢弃有关另一个类的信息,我只能保存一个对象。对于对象序列化我是全新的,我觉得我已经走得很远了。
Author.h :
...
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class Paper;
class Author
{
public:
friend class Paper;
Author( const std::string& last_name_in = "",
const std::string& first_name_in = "",
const std::string& middle_name_in = "" );
...
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & first_name;
ar & last_name;
ar & middle_name;
ar & display_name;
for (int ii = 0; ii < list_of_papers.size(); ii++)
ar & list_of_papers[ii];
}
...
std::string first_name;
std::string last_name;
std::string middle_name;
std::string display_name;
std::vector<const Paper*> list_of_papers;
};
我在Paper.h中没有默认构造函数,因为它没有意义,我真的不知道如何使用它。 的 Paper.h :
...
class Author;
class Paper
{
public:
friend class Author;
Paper( const std::string& paper_title_in,
const std::vector<Author*>& paper_authors_in );
...
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & paper_title;
for (int ii = 0; ii < paper_authors.size(); ii++)
ar & paper_authors[ii];
}
std::string paper_title;
std::vector<Author*> paper_authors;
};
TEST.CPP :
int main()
{
std::ofstream ofs("filename");
{
Author author1("Doe", "John");
Author author2("Dude", "Jim", "J");
std::vector<Author*> list_of_authors;
list_of_authors.push_back(&author1);
Paper other_paper( "A Nice Paper", list_of_authors );
list_of_authors.push_back(&author2);
Paper this_is_my_paper( "What a beautiful paper", list_of_authors );
boost::archive::text_oarchive oa(ofs);
oa << author1;
}
{
Author author_new;
std::ifstream ifs("filename");
boost::archive::text_iarchive ia(ifs);
ia >> author_new;
}
return 0;
}
在Linux中,我用g ++编译:
g++ -o test -I /path/boost/ -L /path/boost/ -lboost_serialization test.cpp author.cpp paper.cpp
在上面提供的表单中,代码不会编译并给我一个巨大的信息。它会在我添加对象序列化之前编译,并且如果我删除'ar&amp; list_of_papers [II];”来自Author.h。
有人能看到我错过的东西吗?
答案 0 :(得分:0)
ar & paper_authors;
应该直接工作,因为boost可以序列化对象的STL容器,前提是对象本身是可序列化的 cf:http://www.boost.org/doc/libs/1_35_0/libs/serialization/doc/tutorial.html#stl