我正在尝试学习一些提升序列化的基础知识。我跟着the tutorial创建了简单的class A
和class B
以及class C
,其中包含A a_;
和B b_;
私有成员。
#include <boost/serialization/serialization.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <string>
#include <fstream>
class A{
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & a_;
}
int a_;
public:
A(){ std::cout << "A constructed" << std::endl; }
A(int a): a_(a) { std::cout << "A constructed with 'a' ==" << a << std::endl; }
};
class B{
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & b_;
}
std::string b_;
public:
B(){ std::cout << "B constructed" << std::endl; }
B(std::string b): b_(b) { std::cout << "B constructed with 'b' ==" << b << std::endl; }
};
class C{
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & a_;
ar & b_;
ar & d_;
}
A a_;
B b_;
double d_;
public:
C(){ std::cout << "C constructed" << std::endl; }
C(int a, std::string b, double d ): a_(a), b_(b), d_(d) { std::cout << "C constructed with 'd' == " << d << std::endl; }
};
int main() {
// create and open a character archive for output
std::ofstream ofs("filename");
// create class instance
C c(15, "rock and roll", 25.8);
// save data to archive
{
boost::archive::text_oarchive oa(ofs);
// write class instance to archive
oa << c;
// archive and stream closed when destructors are called
}
C c_recreated;
{
// create and open an archive for input
std::ifstream ifs("filename");
boost::archive::text_iarchive ia(ifs);
// read class state from archive
ia >> c_recreated;
// archive and stream closed when destructors are called
}
std::cin.get();
}
在IDEone live中,here具有所有奇怪且可怕的编译器错误。在我的VS2010上,我只有两个相同的错误:
Error 2 error C2248: 'C::serialize' : cannot access private member declared in class 'C'
Error 3 error C2248: 'C::serialize' : cannot access private member declared in class 'C'
我做错了什么,如何在class C
和class A
之后使class B
序列化?
答案 0 :(得分:3)
friend class boost::serialization::access;
和B
{/ 1}}没有C
。