Total members 10249 | Gratitudes |It is currently Thu May 17, 2012 8:25 am Login / Join Codemiles


All times are UTC [ DST ]




Post new topic Reply to topic  Quick reply  [ 2 posts ] 
Author Question
 Question subject: overloading << and >>
PostPosted: Sat Nov 08, 2008 3:20 pm 
Offline
Proficient
User avatar

Joined: Sun Oct 19, 2008 3:47 pm
Posts: 281
Has thanked: 0 time
Have thanks: 1 time

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?


TOP
 Profile Send private message  
Reply with quote  
 Question subject: Re: overloading << and >>
PostPosted: Sat Nov 08, 2008 3:22 pm 
Offline
Proficient
User avatar

Joined: Sun Oct 19, 2008 3:53 pm
Posts: 229
Has thanked: 0 time
Have thanks: 0 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.


TOP
 Profile Send private message  
Reply with quote  
Post new topic Reply to topic Quick reply  [ 2 posts ] 
Quick reply


  

 Similar topics
 operator overloading
 unary operator overloading
 Function Overloading
 Operator overloading easy code
 What is Operator Overloading? !!!

All times are UTC [ DST ]


Users browsing similar posts

Users browsing this forum: No registered users and 1 guest



Jump to:  
Previous Question | Next Question 




Home
General Talks
Finished Projects
Code Library
Games
Tutorials

Java
C/C++
C-sharp
php
Script
JSP/Servlets
Ajax
ASP/ASP.net
Google SEO
Database
Communications
Phpbb3 styles
Photoshop tutorials
Flash tutorials
Find a job






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team