0

接口 * base_ptr1 = new Derived1();

接口 * base_ptr2 = new Derived2();

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

4

1 回答 1

0

您可以添加纯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对它们都有效。

于 2021-07-11T08:27:17.853 回答