14.5. OutputΒΆ
As usual when we define a new class, we want to be able to output
objects in a human-readable form. For complex_number objects, we could use
two functions:
void complex_number::print_cartesian ()
{
std::cout << get_real() << " + " << get_imag() << "i" << std::endl;
}
void complex_number::print_polar ()
{
std::cout << get_mag() << " e^ " << get_theta() << "i" << std::endl;
}
The nice thing here is that we can output any complex_number object in
either format without having to worry about the representation. Since
the output functions use the accessor functions, the program will
compute automatically any values that are needed.
The following code creates a complex_number object using the second
constructor. Initially, it is in Cartesian format only. When we invoke
print_cartesian it accesses real and imag without having to
do any conversions.
complex_number c1 (2.0, 3.0);
c1.print_cartesian();
c1.print_polar();
When we invoke print_polar, and print_polar invokes get_mag,
the program is forced to convert to polar coordinates and store the
results in the instance variables. The good news is that we only have to
do the conversion once. When print_polar invokes get_theta, it
will see that the polar coordinates are valid and return theta
immediately.
The output of this code is:
2 + 3i
3.60555 e^ 0.982794i
The active code below uses the print functions for complex_number objects.
Feel free to modify the code and experiment around!
1#include <iostream>
2#include <cmath>
3
4class complex_number
5{
6 double real = 0.0, imag = 0.0;
7 double mag = 0.0, theta = 0.0;
8 bool cartesian, polar;
9
10public:
11 complex_number ();
12 complex_number (double r, double i);
13 void calculate_cartesian ();
14 double get_real ();
15 double get_imag ();
16 void calculate_polar ();
17 double get_mag ();
18 double get_theta ();
19 void print_cartesian ();
20 void print_polar ();
21};
22
23int main() {
24 complex_number c1 (2.0, 3.0);
25 c1.print_cartesian();
26 c1.print_polar();
27}
What is the correct output of the code below?
int main() {
Complex c1 (3.0, 4.0);
// c1.printCartesian();
c1.printPolar();
}