next up previous
Next: The ostream, istream, ofstream Up: canned_classes Previous: Templates: mycomplex.h

The C++ standard complex class

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.h
It 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:




// Illustration of compiler <complex> class.
#include <iostream>
#include <complex>
using namespace std;

typedef complex<double> dcmplx;

int main(){

  dcmplx a(5.,6.),b;

  cout << "Enter b: ";
  cin >> b;

  cout << "a = " << a << "\n";
  cout << "b = " << b << "\n";

  cout << "a + b = " << a + b << "\n";
  cout << "a * b = " << a * b << "\n";
  cout << "a / b = " << a / b << "\n";
  cout << "|a| = "   << abs(a) << "\n";
  cout << "complex conjugate of a = " << conj(a) << "\n";
  cout << "norm of a = " << norm(a) << "\n";
  cout << "abs of a = " << abs(a) << "\n";
  cout << "exp(a) = " << exp(a) << "\n";
}

Notice that we must write #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.


next up previous
Next: The ostream, istream, ofstream Up: canned_classes Previous: Templates: mycomplex.h
Carleton DeTar 2008-11-10