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

时间:2012-04-01 16:27:12

标签: c++

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

#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;&lt;&lt;不会从Base到Child。怎么能重载&lt;&lt;这样,当它的参数在Base中时,它只使用&lt;&lt;的基础版本。 ?

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

2 个答案:

答案 0 :(得分:9)

使其成为虚拟功能。

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(); }
};

答案 1 :(得分:1)

int main(){

Base* B;
B = new Child;

cout << ( Child &) *B << endl;

return 0;

}