简体   繁体   English

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

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

this is a question on overloading the output operator in C++: How do you overload << on BOTH the base class and the derived class? 这是一个关于在C ++中重载输出运算符的问题:如何重载<< on BOTH基类和派生类? Example: 例:

#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;

}

The output is 输出是

To Base: All your child belong to us."

so the name() in Child shadowed that of Base; 所以Child中的name()隐藏了Base的名字; but the overloading of << does not descend from Base to Child. 但是<<的重载不是从基地降到儿童的。 How can I overload << such that, when its argument is in Base it uses ONLY the Base version of << ? 我如何重载<<这样,当它的参数在Base时它只使用<<的基本版本?

I want "To Child: All your child belong to us." 我想要“对孩子:所有孩子都属于我们。” to be output in this case. 在这种情况下输出。

Make it a virtual function. 使它成为一个虚拟功能。

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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM