【问题标题】:How can I serialize an derived type pointer to interface type object in c++?如何在 C++ 中将派生类型指针序列化为接口类型对象?
【发布时间】:2021-09-20 20:29:52
【问题描述】:

接口 * base_ptr1 = new Derived1();

接口 * base_ptr2 = new Derived2();

理论上我应该在所有类中都有 serialize() 方法,但我的接口类型类没有数据成员,只有抽象虚拟方法。

【问题讨论】:

  • "我的接口类型类没有数据成员" 那有什么问题呢?
  • 我使用 boost 进行序列化和 boost::archive 所以我不知道使用 istream 和 ostream
  • 我试图通过阅读这个链接boost.org/doc/libs/1_72_0/libs/serialization/doc/tutorial.html来实现解决方案,所以我找不到任何关于接口类型的信息

标签: c++11 templates interface virtual object-serialization


【解决方案1】:

您可以添加纯virtual 函数来进行序列化。

class Interface {
public:
    virtual void read(std::istream& is) = 0;
    virtual void write(std::ostream& os) const = 0;
};

std::istream& operator>>(std::istream& is, Interface& i) {
    i.read(is);
    return is;
}

std::ostream& operator<<(std::ostream& os, const Interface& i) {
    i.write(os);
    return os;
}

现在,具体类只需要实现readwrite,为Interface 实现的流式操作符将适用于它们。

【讨论】:

  • 非常感谢
猜你喜欢
  • 2014-06-16
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
相关资源
最近更新 更多