72 3 Numerical differentiation and interpolation
T Re ()const; // T real_part = a.Re();
T Im ()const; // T imag_part = a.Im();
T abs ()const; // T m = a.abs(); // modulus
friendComplexoperator+ (constComplex& a,constComplex& b);
friendComplexoperator- (constComplex& a,constComplex& b);
friendComplexoperator*(constComplex& a,constComplex& b);
friendComplexoperator/ (constComplex& a,constComplex& b);
};
What it says is thatComplexis a parameterized type withTas a parameter andThas to be a
type such as double or float. The class complex is now a class template and we would define
variables in a code as
Complex
Complex
Member functions of our class are defined by preceding the name of the function with the
templatekeyword. Consider the function we defined as
Complex:: Complex (doublere_a,doubleim_a)
We could rewrite this function as
template
Complex
{re = re_a; im = im_a;}
The member functions are otherwise defined following ordinary member function definitions.
To write a class like the above is rather straightforward. The class for handling one-
dimensional arrays, presented in the next subsection showssome of the additional possibili-
ties which C++ offers. However, it can be rather difficult to write good classes for handling
matrices or more complex objects. For such applications we recommend therefore the usage
of ready-made libraries like Blitz++ or Armadillo.
Blitz++http://www.oonumerics.org/blitz/is a C++ library whose two main goals are
to improve the numerical efficiency of C++ and to extend the conventional dense array model
to incorporate new and useful features. Some examples of such extensions are flexible stor-
age formats, tensor notation and index placeholders. It allows you also to write several op-
erations involving vectors and matrices in a simple and clear (from a mathematical point
of view) way. The way you would code the addition of two matrices looks very similar to
the way it is done in Fortran. From a computational point of view, a library like Armadillo
http://arma.sourceforge.net/, which contains much of the array functionality included in
Blitz++, is preferred. Armadillo is a C++ linear algebra library that aims towards a good bal-
ance between speed and ease of use. It includes optional integration possibilities with popular
linear algebra packages like LAPACK and BLAS, see chapter 6 for further discussions.
3.3.2 The vector class.
Our next next example is a very simple class to handle one-dimensional arrays. It demon-
strates again many aspects of C++ programming. However, most likely you will end up
using a ready-made array class from libraries like Blitz++ or Armadillo discussed above.
Furthermore, as was the case for the complex class, C++ contains also its own class for one-
dimensional arrays, that is a vector class. At the end however, we recommend that you use
libraries like Armadillo.