开发者

operator<< in derived classes c++

i have a question for the operatorr << in derived clases ex:

if i have

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

is the folowing posible?

class Derived: public Base
{
       //......
       friend ostre开发者_StackOverflow社区am& operator<<(ostream& out,Derived &DERIVEDOBJECT)
       {
           return  out<<DERIVEDOBJECT<<DERIVEDOBJECT.nonderivedvar1 <</*.....*/<< endl;
       }
}

or putting the DERIVEDOBJECT in the << operator won't result in the << recoqnizing it as a reference just to the base class?


What you normally want is something like this:

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

Then a derived class overrides write when/if necessary.


This is going to cause a recursive call:

out<<DERIVEDOBJECT

I would do:

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

PS. Space and lowercase letters are your friends.
By convention identifiers that are all uppercase are macros so you may confuse people by using all uppercase identifiers for normal variables.


You can achieve the expected result by upcasting to the base type:

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"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜