C++:运算符的动态多态性

运算符是否可以具有动态多态性?我有一个基类指针向量:

std::vector<Event*> events;

其中每个事件是一个不同的派生类(例如StartEvent)。所有派生类都有它们的operator<<实现,以便它们可以打印到控制台。

但是,这不起作用:

std::for_each(events.cbegin(), events.cend(), [] (const Event *ev) {
    std::cout << *ev << std::endl;
});

我收到此错误:

error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const Event’)
   std::cout << *ev << std::endl;

我试过这个:

class Event {
protected:
  Event() { }

  virtual std::ostream& operator<< (std::ostream &stream);

public:
  const int32_t timestamp;
};

这没有帮助。如果在派生类中operator<<实现为 a是否有问题friend

  friend std::ostream& operator<< (std::ostream &stream, const StartEvent& se) {

    /* do stuff */
  }

回答

经典的解决方案是将<<重载声明为friend基类的 a ,然后使用它来调用适当的虚方法:

  std::ostream& operator<< (std::ostream &stream, const Event &e) {
      e.format_output(stream);
      return stream;
  }

现在,只需在超类中声明format_output()为普通const virtual方法Event,并在每个子类中覆盖它,以在给定的输出流上格式化类的实例。任务完成。


以上是C++:运算符的动态多态性的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>