Overloading the '<<' Insertion Operator
The operator << is the most commonly overloaded operator, and ironically, the most complex. Just as we use cout to display values of basic data types, we will overload << such that it displays our complex objects. The strange thing about the << operator is that is always operates on a heterogeneous pair of operands: the LHS is "cout" or some other ostream, and the RHS is the class you are trying to output. When an operator function is overloaded as a member function, the LHS is the implicit calling object; here, that would be "cout", which is not a class we can add a member function to. So, the operator << is not overloaded as a member function. Hence it is not a part of our Complex class. However, we do define it in Complex.h and implement in Complex.cpp.
The operator << is a binary operator: the left-hand operand
is the ostream object cout and the right-hand operand is our
Complex object. The prototype of the
operator function for overloading << is:
ostream& operator<< (ostream& out, const Complex& number);
The operator<< can also be implemented as a friend
function. Since we have accessors for our Complex class (
GetReal() and GetImaginary() ), there is no need for making
it a friend function in this case.
The operator<< function is implemented in the following
manner:
-
number
refers to the Complex object we wish to display in cout << number - The left hand side is cout which is passed explicitly, as operator<< is a non-member function.
- You should use the accessors of the Complex class, GetReal() and
GetImaginary(), to get the real part and imaginary part of
number and display them. Note that the output should be
in the form:
Real_part +/- Imaginary_part i. - There is a small complication in outputting the imaginary
part of complex numbers: if it is non-negative, you must output
a '+' between the real and imaginary parts; e.g.:
3 + 2i -3 + 2i 3 - 2i -3 - 2i
Note all four of the above are different numbers.