C++ Library Reference

Type complex

The complex arithmetic library defines one class: class complex. An object of class complex can hold a single complex number. The complex number is constructed of two parts:


class complex {
    double re, im; 
};

The numerical values of each part are held in fields of type double. Here is the relevant part of the definition of complex:

The value of an object of class complex is a pair of double values. The first value represents the real part; the second value represents the imaginary part.

Constructors of Class complex

There are two constructors for complex. Their definitions are:


complex::complex()			{ re=0.0; im=0.0; } 
complex::complex(double r, double i = 0.0)  { re=r; im=i; } 

If you declare a complex variable without parameters, the first constructor is used and the variable is initialized, so that both parts are 0. The following example creates a complex variable whose real and imaginary parts are both 0:


complex aComp;

You can give either one or two parameters. In either case, the second constructor is used. When you give only one parameter, it is taken as the value for the real part and the imaginary part is set to 0. For example:


complex aComp(4.533); 

creates a complex variable with the value:


4.533 + 0i

If you give two values, the first is taken as the value of the real part and the second as the value of the imaginary part. For example:


complex aComp(8.999, 2.333);

creates a complex variable with the value:


8.999 + 2.333i

You can also create a complex number using the polar function, which is provided in the complex arithmetic library (see "Mathematical Functions "). The polar function creates a complex value given a pair of polar coordinates, magnitude and angle.

There is no destructor for type complex.

Arithmetic Operators

The complex arithmetic library defines all the basic arithmetic operators. Specifically, the following operators work in the usual way and with the usual precedence:

+ - / * =

The operator - has its usual binary and unary meanings.

In addition, you can use the following operators in the usual way:

+= -= *= /=

However, these last four operators do not produce values that you can use in expressions. For example, the following does not work:


complex a, b; 
... 
if ((a+=2)==0) {...}; // illegal 
b = a *= b; // illegal 

You can also use the following equality operators in their regular meaning:

== !=

When you mix real and complex numbers in an arithmetic expression, C++ uses the complex operator function and converts the real values to complex values.