operator <<在派生类c ++中

1 c++ derived-class

我对<<派生的clases中的operatorr有一个疑问:

如果我有

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

是下一个可能的?

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

或者将其DERIVEDOBJECT放入<<操作员不会导致<<重新确定它作为基类的参考?

Jer*_*fin 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); 
}
Run Code Online (Sandbox Code Playgroud)

然后,write如果/必要,派生类将覆盖.