繁体   English   中英

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

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

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

#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的名字; 但是<<的重载不是从基地降到儿童的。 我如何重载<<这样,当它的参数在Base时它只使用<<的基本版本?

我想要“对孩子:所有孩子都属于我们。” 在这种情况下输出。

使它成为一个虚拟功能。

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