接口 * base_ptr1 = new Derived1();
接口 * base_ptr2 = new Derived2();
理论上我应该在所有类中都有 serialize() 方法,但是我的接口类型类没有数据成员,只有抽象虚拟方法。
接口 * base_ptr1 = new Derived1();
接口 * base_ptr2 = new Derived2();
理论上我应该在所有类中都有 serialize() 方法,但是我的接口类型类没有数据成员,只有抽象虚拟方法。
您可以添加纯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;
}
现在,具体的类只需要实现read
,write
并且实现的流式操作符Interface
对它们都有效。