抽象类重载ostream运算符

ban*_*era 0 c++ virtual overloading abstract ostream

我有一个基本的抽象类Base.

class Base
{
protected:
    string m_Name;
public:
    virtual string Name() { return m_Name; }
    virtual string Type() = 0;
    virtual bool isEqual(Base* rhs) = 0 ;
    //virtual ostream& operator<< (ostream& out) const;
};
Run Code Online (Sandbox Code Playgroud)

我想重载operator <<显示继承的对象Base.我不能使用void print()函数,因为这些继承的对象Base也有一些只能显示的对象operator <<.

我怎么能超负荷operator <<

jua*_*nza 5

一种常见的模式是提供虚拟print方法,并在ostream&<<运算符中使用它:

class Base
{
 public:

  void print(std::ostream& o) const { /* do your stuff */ }
  virtual ~Base() {}
};

std::ostream& operator<<(std::ostream& o, const Base& b)
{
  b.print(o);
  return o;
}
Run Code Online (Sandbox Code Playgroud)

这个想法是每个派生类型print(ostream&)根据其需要实现.