C++ 覆盖运算符<<在继承的类中

C++ override operator<< in inherited class

本文关键字:lt 继承 覆盖 C++ 运算符      更新时间:2023-10-16

我有一个基类,其中覆盖了<<运算符。

    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。我有一个继承的 Abonne 类,名为 Etudiant。我希望再次覆盖 Etudiant 类中的 <<运算符,但我希望它在 Etudiant 类的定义中调用基类 Abonne 的运算符<<,并添加更多。我试过这个:

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

它不起作用,召回自身的<<并递归直到崩溃。

我应该怎么做?

谢谢。

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

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