10

Having an issue with this particular method and not sure how to resolve it! The error I'm getting is the above:

"error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>' C:\Program Files\Microsoft Visual Studio 10.0\VC\include\ostream 604"

My method is:

ostream operator<<( ostream & stream, ProcessClass const & rhs )
{
  stream << rhs.name_;
  return stream;
}

And in the header:

friend std::ostream operator<<( std::ostream & stream, ProcessClass const & rhs );

Any ideas on how to resolve this? I think it is something to do with passing by reference instead of value... but I'm a bit confused!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
Fids
  • 151
  • 1
  • 3
  • 10

2 Answers2

12

The return type should be ostream & which is a reference to ostream.

ostream & operator<<( ostream & stream, ProcessClass const & rhs )
{    //^^^ note this!
  stream << rhs.name_;
  return stream;
}

When you return by value (instead of reference), then that requires copying of stream object, but copying of any stream object in C++ has been disabled by having made the copy-constructor1 private.

1. and copy-assignment as well.

To know why copying of any stream has been disabled, read my detail answer here:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Now the confusing thing is (and I'm not sure what I am missing) is when I change it to above (which I had tried before) I then get an error... `error C2556: 'std::ostream &operator <<(std::ostream &,const ProcessClass &)' : overloaded function differs only by return type from 'std::ostream operator <<(std::ostream &,const ProcessClass &)'` NB. I have slightly modified the code, but go along with the code as above, the error is produced either way upon compilation. – Fids Aug 23 '11 at 13:57
  • 1
    @Fids: You've defined two times in your class. Why have you defined it two times? – Nawaz Aug 23 '11 at 14:26
4

You cannot copy streams, instead return a reference, change to

ostream& operator<<( ostream & stream, ProcessClass const & rhs )
john
  • 85,011
  • 4
  • 57
  • 81