3.3 Classes in C++ 71
inlineComplexoperator(constComplex& a,constComplex& b)
{
returnComplex(a.reb.re - a.imb.im, a.imb.re + a.re*b.im);
}
It will be convenient to inline all functions used by this operator. To inline the complete
expressiona*b;, the constructors andoperator=must also be inlined. This can be achieved
via the following piece of code
inlineComplex:: Complex (){re = im = 0.0;}
inlineComplex:: Complex (doublere,double im)
{...}
inlineComplex:: Complex (constComplex& c)
{...}
inlineComplex::operator= (constComplex& c)
{...}
// e, c, d are complex
e = cd;
// first compiler translation:
e.operator= (operator(c,d));
// result of nested inline functions
// operator=, operator, Complex(double,double=0):
e.re = c.red.re - c.imd.im;
e.im = c.imd.re + c.re*d.im;
The definitionsoperator-andoperator/follow the same setup.
Finally, if we wish to write to file or another device a complexnumber using the simple
syntaxcout << c;, we obtain this by defining the effect of<<for a Complex object as
ostream&operator<< (ostream& o,constComplex& c)
{o <<"("<< c.Re() <<","<< c.Im() <<") ";returno;}
3.3.1.2 Templates
The reader may have noted that all variables and some of the functions defined in our class
are declared as doubles. What if we wanted to make a class which takes integers or floating
point numbers with single precision? A simple way to achievethis is copy and paste our class
and replacedoublewith for exampleint.
C++ allows us to do this automatically via the usage of templates, which are the C++
constructs for parameterizing parts of classes. Class templates is a template for producing
classes. The declaration consists of the keywordtemplatefollowed by a list of template ar-
guments enclosed in brackets. We can therefore make a more general class by rewriting our
original example as
template
classComplex
{
private:
T re, im;// real and imaginary part
public:
Complex (); // Complex c;
Complex (T re, T im = 0);// Definition of a complex variable;
Complex (constComplex& c); // Usage: Complex c(a); // equate two complex variables
Complex&operator= (constComplex& c);// c = a; // equate two complex variables, same
as previous
~Complex (){} // destructor