// complex.h - a class template for complex numbers // from Nagler, Learning C++ (2004), start p. 358 #ifndef COMPLEX_H #define COMPLEX_H #include using namespace std; template // default template argument class Complex { // implicit inline friend for insertion operator friend ostream &operator<< (ostream &out, Complex const &arg) { return out << arg.real << " + " << arg.imag << 'i'; } public: Complex(T const &real = T(), T const &imag = T()); Complex(Complex const &); ~Complex(); static int getCount() { return counter; } private: T real, imag; static int counter; }; // implementation is here, not in a separate file (i.e., no complex.cpp) template // basic, default, and converting ctor (p. 360) Complex::Complex(T const &real, T const &imag) : real(real), imag(imag) { ++counter; } template // copy ctor Complex::Complex(Complex const &o) : real(o.real), imag(o.imag) { ++counter; } template // dtor (added to example to manage the counter) Complex::~Complex() { --counter; } template // initialize static variable int Complex::counter = 0; #endif