Boost使用指向对象的指针向量(C++-linux)

Boost with vectors of pointers to object (C++ - linux)

本文关键字:向量 指针 C++-linux 对象 Boost      更新时间:2023-10-16

我正在研究一个组织论文的代码。我有两个类(Author和Paper),它们通过包含和指针相互连接。我为这两个类都定义了序列化,但只有放弃关于另一个类的信息,才能保存对象。我对对象序列化完全陌生,我觉得我已经尽了最大努力。

作者.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中没有默认构造函数,因为它没有意义,我真的不知道该如何使用它。纸张.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&文件列表[ii];'来自Author.h.

有人能看到我缺了什么吗?

ar & paper_authors;

应该直接工作,因为boost可以序列化对象的STL容器,前提是对象本身是可串行的cf:http://www.boost.org/doc/libs/1_35_0/libs/serialization/doc/tutorial.html#stl