运营商LT;<在派生类c ++中

时间:2011-04-20 21:53:01

标签: c++ derived-class

我在派生的clases ex:

中有一个操作员<<的问题

如果我有

class Base
{
      //......
      friend ostream& operator<<(ostream& out,Base &B)
      {
          return  out<<B.x<<B.y<</*........*/<<endl;
      }
      //......    
};

是下属的?

class Derived: public Base
{
       //......
       friend ostream& operator<<(ostream& out,Derived &DERIVEDOBJECT)
       {
           return  out<<DERIVEDOBJECT<<DERIVEDOBJECT.nonderivedvar1 <</*.....*/<< endl;
       }
}

或将DERIVEDOBJECT放在<<运算符中不会导致<<将其重新定义为基类的参考?

3 个答案:

答案 0 :(得分:10)

你通常想要的是这样的:

class Base { 

     virtual std::ostream &write(std::ostream &os) { 
         // write *this to stream
         return os;
     }
};

std::ostream &operator<<(std::ostream &os, Base const &b) { 
     return b.write(os); 
}

然后,如果需要,派生类会覆盖write

答案 1 :(得分:1)

这将导致递归调用:

out<<DERIVEDOBJECT

我愿意:

   friend ostream& operator(ostream& out,Derived &DERIVEDOBJECT)
   {
       return  out << static_cast<Base&>(DERIVEDOBJECT)
                   << DERIVEDOBJECT.nonderivedvar1
                   <<.....<< endl;
   }

PS。空格和小写字母是你的朋友 按照惯例,全部大写的标识符都是宏,因此您可以通过使用正常变量的所有大写标识符来混淆人们。

答案 2 :(得分:0)

您可以通过 upcasting 到基类型实现预期结果:

struct base {};
std::ostream& operator<<( std::ostream& o, base const & b ) {
   return o << "base";
};
struct derived : base {};
std::ostream& operator<<( std::ostream& o, derived const & d ) {
   return o << static_cast<base&>(d) << " derived";
}
int main() {
   derived d;
   std::cout << d << std::endl; // "base derived"
}