Class Templates

collections of objects. These are the data structures studied in CMSC 341.

SmartArray re-revisited

The SmartArray class we designed earlier in the semester contain a dynamically allocated array of integers. We could specify the maximum size as a parameter, rather than in the constructor. template <class T, int size> class SmartArray { public: SmartArray ( void ); // other members private: int m_size; T *m_theData; // array of any type };

Each of the SmartArray methods is a function template

// SmartArray constructor template <class T, int size> SmartArray<T, int>::SmartArray ( void ) { m_size = size; m_theData = new T [m_size]; // an array of Ts using T's default constructor } //----------------------------------- // copy constructor //----------------------------------- template <class T, int> SmartArray<T, int>::SmartArray (const SmartArray<T>& array) { m_size = array.m_size; m_theData = new T [ m_size ]; for (int j = 0; j < m_size; j++ ) m_theData[ j ] = array.m_theData [ j ]; }

Using the SmartArray class template

In the main program,

#include "SmartArray.H"

Define some SmartArrays:

SmartArray<float, 10> array1; SmartArray<myClass, 20> array2;

Sorry! We could not find what you were looking for

Try going back to the main page here

 
4
4
0
0
0
0