Switch to full style
For C/C++ coders discussions and solutions
Post a reply

overloading << and >>

Sat Nov 08, 2008 3:20 pm

I've been doing some operator overloading and i've pretty much
covered the whole thing, except the insertion and extraction
operators.

I've got two questions:
1. I've seen in my book as well as many sites on line that those two
operators can only be overloaded using friend functions. Can't we use
member functions instead? I've tried doing it... but didn't up come
with a way of refering to streams inside the function...

2. The two operators (<< and >>) are binary operators. By obvious
logic, the function of the overloaded binary operator should always
return a value. for the operators << and >> where is this value
returned to.

I'll illustrate:

Code:
complex complex :: operator + (complex & x)
{
complex temp;
temp.real = x.real + real;
temp.imag = x.imag + imag;
return (temp);
}

ostream & operator << (ostream & toout,complex x)
{
if (x.imag < 0)
toout<<x.real << " - " <<abs(x.imag)<<"i"<<endl;
else
toout<<x.real << " + " <<x.imag<<"i"<<endl;
return(toout);
}

say we've in the main function

cout<<a;
where a is an object of class complex, initialized properly.


in the function above, or to what does the function return to?



Re: overloading << and >>

Sat Nov 08, 2008 3:22 pm

They should return a stream. The stream returned allows you to chain
the operators:
Code:
cout << "string " << 1;


If they didn't return the stream the above wouldn't work - you'd only
be able to use one <<.

You typically return the stream that was passed in.

Post a reply
  Related Posts  to : overloading << and >>
 Function Overloading     -  
 operator overloading     -  
 What is Operator Overloading? !!!     -  
 unary operator overloading     -  
 Operator overloading easy code     -