Sun Studio 12: C++ User's Guide

15.2 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 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.

15.2.1 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 specifying 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, that parameter 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 following value:

4.533 + 0i

If you give two values, the first value 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 following 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 15.3 Mathematical Functions). The polar function creates a complex value given the polar coordinates magnitude and angle.

There is no destructor for type complex.

15.2.2 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 subtraction operator (-) has its usual binary and unary meanings.

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

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

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

You can also use the equality operator (==) and the inequality operator (!=) 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.