Total members 11894 |It is currently Thu Nov 21, 2024 4:24 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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?




Author:
Proficient
User avatar Posts: 280
Have thanks: 1 time

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.

_________________
Please recommend my post if you found it helpful


Author:
Proficient
User avatar Posts: 228
Have thanks: 0 time
Post new topic Reply to topic  [ 2 posts ] 

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



cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com