C++/overloading << and >> operators
Expert: vijayan - 11/3/2008
Question
Hello, Vijayan
I know that in order to overload the << and >> operators I must do sth like this inside my class:
friend ostream operator<<(ostream& out, const ClassType&);
friend istream operator>>(istream& in, ClassType&);
I've been able to use this in my programs, but I dont understand how this works inside the compiler.
What I mean is, how and when do the 2 args get sent to the functions??
So in my main prog, i would have sth like this
cout<<object;
cin>>object;
how does the compiler interpret this??
Thanks
Answerthe overloaded << operator is used by the compiler this way.
note: C++ streams are not copyable; you must return references.
with:
ostream& operator<<(ostream& out, const ClassType&);
istream& operator>>(istream& in, ClassType&);
void foo( ostream& out, istream& in, ClassType& object )
{
out << object ; // is interpreted as the next statement
operator<< ( out, object ) ;
in >> object ; // is interpreted as the next statement
operator>> ( in, object ) ;
}
in general, if @ is a placeholder for a binary operator overloaded via a free function,
a @ b ;
is evaluated by the compiler as:
operator@ ( a, b ) ;