Post by Sabetay TorosHi,
class Complex
{
double re, im;
...
ostrstream& operator<<(ostrstream& os, Complex& Complex);
}
I'm a little confused [...]
So am I by the above code.
It declares an 'operator<<()' as a /member/ function. Thus
that operator would take three arguments: A 'Complex' (aka
the '*this' argument implicit to all member functions), an
'ostrstream', and another 'Complex'. However, 'operator<<()'
only ever takes two arguments -- so the code cannot compile.
Let's sort this out.
First, on the left side of an '<<' operator invocation (when
used for streaming) is a stream. Since for member functions
the leftmost argument always is '*this', if you want to
implement a stream operator as a member function, it needs
to implemented as a member of the stream class. If you want
to use the standard library's stream classes, you cannot do
this. Stream custom operators are thus best implemented as
free functions.[1]
Also, the right-hand side object of a stream operator is not
modified. Therefor it should be passed as a 'const' parameter.
Otherwise you won't be able to stream out a 'const' Complex
object for no good reason.
Further, writing into a string stream is not different from
writing into a file stream or any other 'std::ostream'. So
why not use 'std::ostream' on the left side? It allows you
to pass in a string stream as well as any other output stream.
You gain more general usability with no effort.
Last, but not least, 'std::ostrstream' seems not a very good
choice as a string stream class. It's deprecated, and there
are very good reasons for it. Generally, you'd better use
'std::ostringstream' from the header <sstream>. (However,
according to the paragraph immediately above this one, this
decision is best left to the /users/ of your stream operator,
not the implementer, so it's actually moot to discuss it here.)
If we combine this, we have
class Complex;
std::ostream operator<<(std::ostream& os, const Complex& c);
(which could be implemented as Sergiy suggested).
Schobi
[1] My rule of thumb for binary operator that can, syntactically,
be implemented either as a member function or a free function:
If it modifies its left argument, make it a member, otherwise
make it a free function.
--
***@gmx.de is never read
I'm HSchober at gmx dot de
"I guess at some point idealism meets human nature and
explodes." Daniel Orner