A natural operation we might want to perform on complex numbers is addition. If the numbers are in Cartesian coordinates, addition is easy: you just add the real parts together and the imaginary parts together. If the numbers are in polar coordinates, it is easiest to convert them to Cartesian coordinates and then add them.
Complex add (Complex& a, Complex& b)
{
double real = a.getReal() + b.getReal();
double imag = a.getImag() + b.getImag();
Complex sum (real, imag);
return sum;
}
Notice that the arguments to add are not const because they might be modified when we invoke the accessors. To invoke this function, we would pass both operands as arguments:
This active code uses the add function for Complex objects. As an exercise, write the subtract function for Complex objects in the commented area of the active code. If you get stuck, you can reveal the hint below for help. Once you are finished, feel free to modify the code and experiment around!