【问题标题】:C++ override operator<< in inherited classC ++覆盖继承类中的运算符<<
【发布时间】:2016-02-21 13:37:33
【问题描述】:

我有一个基类,其中覆盖了

    friend std::ostream& operator<<(std::ostream& out, const Animal& animal);
    ostream & operator<<(ostream & out, const Animal& animal)
{
    out << animal.age << "," << animal.size << endl;
}

这是在我的 Abonne 类的 .h 中。我有一个名为 Etudiant 的 Abonne 类的继承类。我希望再次覆盖 Etudiant 类中的

    friend ostream& operator<<(ostream& out, const Dog& dog);

ostream& operator<<(ostream& out, const Dog& dog)
{
    return out << dog << endl;
}

它不起作用,调用自身的

我应该如何进行?

谢谢。

【问题讨论】:

  • “我有一个基类,其中包含对 关于此语句的所有内容都是错误的。
  • 创建一个可与类限定符一起使用的put() 函数。

标签: c++ stream operator-overloading


【解决方案1】:

简单!您需要调用采用Abonne 的版本。所以只需这样做:

return out << static_cast<const Abonne&>(etudiant) << " ... and more" << endl;
//            ^^^^^^^^^^^^^^^^^^^^^^^^^^

【讨论】:

  • 谢谢 :) 你知道另一种不用强制转换的方法吗? Abonne::operator
  • 你知道在函数不是全局的情况下是否可以吗?
  • @TheBlueWizard:会的。
猜你喜欢
  • 1970-01-01
  • 2011-08-27
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
相关资源
最近更新 更多