Operator Overloading Question

Im new to this site but it seemed like a good place for programming questions.

This is the assignment I am working on:

Design, implement, and test a class “Complex” which uses the followings overloaded operators for complex number: >>, <<, +, –, *, and /.

The complex number is described as having a real component or real part a and an imaginary component or imaginary part b where i2 = -1: A = a + bi

Given the two complex numbers A and B then the following definition will help to overload the operators. For any pair of complex numbers apply all overloaded operators.

A = a + bi

B = c + di

>> It extracts two part of complex number.

<< It inserts the complex number with (a) + (b) i format.

+ A+B = (a + c) + (b + d)i

- A - B = (a - c) + (b - d)i

* A* B = (ac - bd) + (bc + ad)i

/ A / B = (ac + bd)/(c2 + d2)+ (bc -ad)/(c2 + d2)i

Plan 3P-I/O & Note (only for files) and test data for client program.

Input Sample:

2.5 -2.2

1.0 1.0

Output Sample:

A = (2.5) + (-2.2) i

B = (1.0) + (1.0) i

A + B = (3.5) + ( -1.2) i

A - B = .. . .

A * B = .. . .

A / B = .. . .

I just dont really understand the whole operator overloading thing and was wondering if anyone had any pointers to completing this assignment.

Re: Operator Overloading Question

All the operators you have to write should be written as nonmember friend functions.

Operator overloading is just syntactic sugar for function calls.

Assuming correct class design and a class complex_num....

friend complex_num operator + ( const complex_num& lhs, const complex_num& rhs )

{ /* code here for adding two complex_nums together */ }

should be in your class for each operator you have to overload. The << and >> are slightly different.....

friend std::ostream& operator << ( std::ostream& lhs, const complex_num& rhs )

{ /* code here to print out your complex_num then return lhs */}

friend std::istream& operator >> ( std::istream& lhs, complex_num& rhs )

{ /* code here to input your complex_num then return lhs */}

now for instance when you write...

Code:

`complex_num a( 4,3 ) , b ( 5,2 ) , result;`

result = a + b; // this line calls operator +(complex_num, complex_num)

see now?

Re: Operator Overloading Question

Quote:

Originally Posted by **smcheval**

All the operators you have to write should be written as nonmember friend functions.

That is true, unless you have member functions to get the real and imaginary portions separately, in which case all the operators can be non-member **non-friend** functions. Or, if you are allowed to add your own operators, then implement operator+=, operator-=, operator*= and operator/= as member functions, then implement operator+, operator-, operator* and operator/ as non-member non-friend functions in terms of the respective assignment operators.