当我尝试序列化具有 protected 成员的类时,出现以下错误: “无法访问在类 NetElement 中声明的 protected 成员”。这个想法是我想在类定义之外有一个序列化函数。我究竟做错了什么?
最好的问候, 威力多多
这是代码...
// class definition
class NetElement
{
friend class boost::serialization::access;
protected:
int nelements;
int ids;
public:
static NetElement* New(){return new NetElement;}
virtual void Delete(){delete this;}
protected:
NetElement(){};
~NetElement(){};
};
// nonintrusive serialize
template<class Archive>
void serialize(Archive & ar, NetElement& element, const unsigned int version=1)
{
ar & element.nelements & element.ids;
}
int main(void)
{...
std::ofstream os("Pipe1.txt");
boost::archive::text_oarchive oa(os);
serialize(oa,el/*ref to NetElementObj*/);
...
}
最佳答案
您已经通过添加“friend”行展示了您自己正在更改类(如果类中没有序列化函数,它对您没有任何作用)。
如果无法更改类,您将陷入更脆弱的解决方案(这是我曾经不得不做的一个,我并不为此感到自豪(但它确实显示了保护优于私有(private)的全部意义))
#include <boost/archive/text_oarchive.hpp>
#include <fstream>
// class definition
class NetElement
{
protected:
int nelements;
int ids;
public:
static NetElement* New(){return new NetElement;}
virtual void Delete(){delete this;}
protected:
NetElement(){};
~NetElement(){};
};
class NetElementS : public NetElement
{
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & nelements & ids;
}
};
int main(void)
{
NetElement *el = NetElement::New();
std::ofstream os("Pipe1.txt");
boost::archive::text_oarchive oa(os);
oa & *reinterpret_cast<NetElementS *>(el);
}
关于c++ - 促进对 protected 数据的序列化访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1687579/