重载基类及其派生类(C++)的输出运算符

Overloading the output operator for both the base class and its derived class (C++)

本文关键字:C++ 输出 运算符 基类 派生 重载      更新时间:2023-10-16

这是一个关于在C++中重载输出运算符的问题:如何使<lt;在基类和派生类上?示例:

#include <iostream>
#include <cstdlib>
using namespace std;

class Base{
public:
virtual char* name(){ return "All your base belong to us.";}
};
class Child : public Base{
public:
virtual char* name(){ return "All your child belong to us.";}
};

ostream& operator << (ostream& output, Base &b){
output << "To Base: " << b.name() ;
return output;}
ostream& operator << (ostream& output, Child &b){
output << "To Child: " << b.name() ;
return output;}

int main(){
Base* B;
B = new Child;
cout << *B << endl;
return 0;
}

输出为

To Base: All your child belong to us."

所以Child中的name()在Base中的后面;但是<lt;不会从Base下降到Child。我怎么能超载<lt;使得当其参数在Base中时,其仅使用<lt?

我想在这种情况下输出"致孩子:你所有的孩子都属于我们"。

使其成为一个虚拟函数。

class Base{
public:
  virtual const char* name() const { return "All your base belong to us.";}
  inline friend ostream& operator<<(ostream& output, const Base &b)
  {
    return b.out(output);
  }
private:
  virtual ostream& out(ostream& o) const { return o << "To Base: " << name(); }
};
class Child : public Base{
public:
  virtual const char* name() const { return "All your child belong to us.";}
private:
  virtual ostream& out(ostream& o) const { return o << "To Child: " << name(); }
};
int main(){
Base* B;
B = new Child;
cout << ( Child &) *B << endl;
return 0;
}