C++ 覆盖运算符<<在继承的类中
C++ override operator<< in inherited class
我有一个基类,其中覆盖了<<运算符。
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;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 头文件-继承c++
- 呼叫运营商<<临时
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- <<操作员在下面的行中工作
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- C++继承运算符<<
- & lt; & lt;使用继承和模板定义