我们可以通过< >指定一种数据类型,从而创建出一个模板类的实例。有了前面定义的模板类,如果我们想创建一个 int 数组可以按照如下方式使用模板类:
array<int> a(10);
array 表明用 int 类型来代替模板类中的类参数“T”,编译器会将模板类 array 中所有的类参数 T 都用 int 来代替。例如类中的私有成员变量T * num;会被替换为int * num;。对类中的成员函数也会进行相同的替换,如T & operator;将会被替换为int & operator;。
如果我们定义对象:
array<double> D(10);
则模板类中所有的类参数“T”都将被换为 double。我们将 array 和 array 称为模板类的实例。使用这些实例就与使用普通类是一样的。
#include <iostream>using namespace std;template< class T >class array{public:array( int );T & operator[]( int );const T & operator[] ( int )const;int getlen() const {return length; }~array();private:array(){};int length;T * num;};template < class T >array< T >::array( int n ){num = new T[n];length = n;}template < class T >array< T >::~array(){delete[] num;}template< class T >T & array< T > ::operator[] ( int i ){if( i < 0 || i >= length )throw string( "out of bounds" );return num[i];}template< class T >const T & array< T > ::operator[] (int i) const{if( i < 0 || i >= length)throw string( "out of bounds" );return num[i];}template< class T >ostream & operator<<( ostream & out, const array <T> & A ){for(int i=0; i < A.getlen(); i++)out<< A[i] << " ";return out;}int main(){array< int > A(10);for(int i = 0; i < 10; i++){A[i] = 2*i; }cout<<A<<endl;return 0;}