Tuesday, July 14, 2009

C++: overloading the <<, >> and == operators.?

I'm making a class that can handle complex numbers. That's the ones with i in them so an example would be 5 + 2i.





So the class has 2 private variables real and imag.


I overloaded the +,-,*,/ and = operators but can't figure out how to do the %26lt;%26lt; , %26gt;%26gt; and ==.





so what I need to be able to do is say.


if (Complex1 == Complex2)


cout %26lt;%26lt; "the numbers are equal";





and:





cout %26lt;%26lt; Complex1;





and:





cin %26gt;%26gt; Complex1;





Heres how I did the +. It should look similar to that. If you could give an example of how to overload the %26lt;%26lt;, %26gt;%26gt;, == I would be really grateful. (please don't just link me to a site you found I've already been to about 5)





class Complex


{


double real;


double imag;


public:


Complex operator +(Complex Num);


}





Complex Complex :: operator +(Complex Num)


{


Complex Temp;





Temp.real = real + Num.real;


Temp.imag = imag + Num.imag;





return Temp;


}

C++: overloading the %26lt;%26lt;, %26gt;%26gt; and == operators.?
You have to use friend functions:





Header file:





class Point {


friend ostream%26amp; operator%26lt;%26lt;(ostream%26amp; output, const Point%26amp; p);


public:


. . .


private:


. . .





And the main:





ostream%26amp; operator%26lt;%26lt;(ostream%26amp; output, const Point%26amp; p) {


output %26lt;%26lt; "(" %26lt;%26lt; p.x %26lt;%26lt; ", " %26lt;%26lt; p.y %26lt;%26lt;")";


return output;





}





Unless you do not need a reference to private data members.
Reply:I forget the specifics of complex numbers but you want to do something like this (or whatever equality means in complex numbers):





bool Complex::operator==(const Complex%26amp; rhs ) const


{


return( (this.real == rhs.real) %26amp;%26amp; (this.imag == rhs.imag) );


}





You may want to later want to compare Complex with some other kind of variable like double, int or whatever. In that case you need to declare another operator== and code it for that type.





The stream ops go like this, though you are the one to decide exactly how you want to code the input and output. Since they are global functions you need to declare them as friends in the Complex class so that they can access the private vars of Complex.





ostream %26amp;operator%26lt;%26lt;(ostream %26amp;stream, const Complex %26amp;c)


{


stream %26lt;%26lt; c.real %26lt;%26lt; c.imag;





return(stream);


}





istream %26amp;operator%26gt;%26gt;(istream %26amp;stream, Complex %26amp;c)


{


stream %26gt;%26gt; c.real %26gt;%26gt; c.imagine;





return(stream);


}


No comments:

Post a Comment