【正文】
Array T a1( 50 )。 //... } 例子: template class T class Array { //... }。 //array of 100 doubles a1[ 6 ] = 。 } 模板實(shí)例 include iostream using namespace std。 i++ ) os ar[ i ] endl。 ar) { for ( int i = 0。 operator ( ostreamamp。 } template class T Array T ::~Array() { delete [] a。 } return a[i]。 Array T ::operator[] ( int i ) const { if (i 0 || i = size) { cerr index i Out of bounds: 。 } return a[i]。 Array T ::operator [] ( int i ) { if (i 0 || i = size) { cerr index i Out of bounds: 。 //arbitrary value }。 Array()。 } private: T* a。 ~Array()。 operator[] ( int ) const。 operator [] ( int )。 } intArray::~intArray() { delete [] a。 } return a[i]。 intArray::operator[] ( int i ) const { if (i 0 || i = size) { cerr index i Out of bounds: 。 } return a[i]。 intArray::operator [] ( int i ) { if (i 0 || i = size) { cerr index i Out of bounds: 。 //arbitrary value }。 intArray()。 } private: int* a。 ~intArray()。 operator[ ] ( int ) const。 operator [ ] ( int )。模板與標(biāo)準(zhǔn)模板庫(kù) 代碼重用的另一種方式:模板類 模板的基本知識(shí) 一個(gè)模板類至少具有一個(gè)類參數(shù),類參數(shù)是個(gè)符號(hào)以表示將要被某個(gè)確定數(shù)據(jù)類型代替的類型。 class intArray { public: intamp。 const intamp。 intArray( int )。 int get_size() const { return size。 int size。 //*** for emphasis int dummy_val。 intamp。 return dummy_val。 } const intamp。 return dummy_val。 } intArray::intArray( int s ) { a = new int[ size = s ]。 } // // 模板類方式 // template class T class Array { public: Tamp。 const Tamp。 Array( int )。 int get_size() const { return size。 int size。 //*** for emphasis T dummy_val。 template class T Tamp。 return dummy_val。 } template class T const Tamp。 return dummy_val。 } template class T Array T ::Array( int s ) { a = new T[ size = s ]。 } template class T ostreamamp。 os, const Array T amp。 i ()。 return os。 //declaration of template class Array int main() { Array double a1(100)。 couta1[6]endl。 Array a0(50)。 template class T Array T a2( 50 )。 參數(shù)表中的模板類 模板類可以作為一種數(shù)據(jù)類型出現(xiàn)在參數(shù)表中。 operator ( ostreamamp。 ar) { for ( int i = 0。 i++ ) { os ar[ i ] endl。 } 函數(shù)模板 template class T T Max(T t[ ], int n) { int i = 0。 for (