提升对受保护数据的序列化访问

dod*_*dol 2 c++ boost-serialization

当我尝试使用受保护的成员序列化类时,我收到以下错误:"无法访问类NetElement中声明的受保护成员".我的想法是,我希望在类定义之外有一个序列化函数.我究竟做错了什么?

最好的问候,mayydodol


这是代码......

// 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*/);
 ...
}
Run Code Online (Sandbox Code Playgroud)

McB*_*eth 5

你已经通过添加"朋友"行来显示你自己改变了这个类(如果没有序列化函数在类中,你就不会为你做任何事情).

如果不能改变课程,你就会陷入更脆弱的解决方案(这是我必须做的一次,我不为之骄傲(但它确实显示了保护私人的全部意义))

#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);
}
Run Code Online (Sandbox Code Playgroud)