c++ - 促进对 protected 数据的序列化访问

标签 c++ boost-serialization

当我尝试序列化具有 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/

相关文章:

c++ - 在 Cocoa 上创建后窗口消失

c++ - boost::archive::binary_iarchive 签名无效

c++ - 序列化 `std::type_index`

c++ - 使用常量和非常量函数 - C++

c++ - 如何读入文件并将该文件分类为不同类型的数据,所有数据都存储在结构中的特定数组中

python - 如何使用 native Python/C API 从 C++ 创建 python 自定义类型?

c++ - 促进树的序列化?

c++ - 具有 boost::shared_ptr 类型成员的 std::map 序列化失败

android - 使用 boost 编译 android 应用程序,未定义对 'mbtowc' 的引用

c++ - 来自 boost asio io_service get_service() 的错误指针