Most C++ compilers provide a complex class. The GNU g++ compiler defines one. On our machines you can find it in
/home/share/include/g++/std/complext.hIt is templatized, just like ours in the previous subsection. But it has several additional useful features. Here is an example of how you can use it:

#include <complex>
with angle brackets and not with quotes, as we did when we wanted
our own version. In this illustration we have defined our own
shorthand dcmplx
for a double complex number, working
with the template. However, we could have just as well used the double_complex
type that is already typedef'ed to complex<double>
in the complex
header file.
The canned complex class provides several features that our own class
did not. Among them are the ability to use cin
and cout
with complex variables. In addition to the usual
arithmetic operations, several math functions, such as exp
, are also defined. To prevent surprises, it is a good
idea to test the conventions for these functions before using
them. For example, notice that <b>norm</b> gives the sum of the
squares of the real and imaginary parts, whereas <b>abs</b> gives the
square root of <b>norm</b>.
In the above example we use cin
to read in the value of
b
. To specify the real and imaginary parts of a complex
number number, the input format uses parentheses and a comma as in
(real,imag)
. For example (1.,7.)
The
output format is the same. An input single real number is converted
to a complex number with a zero imaginary part, as one would expect.
To get the real and imaginary parts, use the class methods real() and imag(). For example, if a is an instance of a standard complex object, then a.real() gives its real part.
It is left as an exercise to glance through the header file and find other functions defined for this class.