template 模板應用實例

// Arrat.h

template <typename T>   //定義類模板
class Array
{
public:
 Array(int s);
 virtual ~Array();
 virtual T& Entry(int index);
 virtual void Enter(int index,const T& value);
protected:
 int size;
 T *element;       //數據成員是T類型指針
};

// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream.h"
#include "Arrat.h"

template <typename T>  //定義函數模板,動態申請數組空間
Array<T>::Array(int s)  
{
 if(s>1) size=s;
 else size=1;
 element=new T[size];
}

template <typename T>  //定義函數模板,釋放數組空間
Array<T>::~Array()
{
 delete [] element;
}

template <typename T>  //定義函數模板,返回第index元素值
T& Array<T>::Entry(int index)
{
 return element[index];
}

template <typename T>  //定義函數模板,向數組的第index單元賦值
void Array<T>::Enter(int index,const T& value)
{
 element[index]=value;
}


int main(int argc, char* argv[])
{
 Array<int> IntAry(5);            //用int實例化,建立類模板對象
 int i;
 for (i=0;i<5;i++)
  IntAry.Enter(i,i);
 cout<<"Integer Array:"<<endl;
 for (i=0;i<5;i++)
  cout<<IntAry.Entry(i)<<'/t';
 cout<<endl;
 Array<double> DouAry(5);         //用double實例化,建立模板類對象
 for(i=0;i<5;i++)
  DouAry.Enter(i,(i+1)*0.35);
 cout<<"Double Array:"<<endl;
 for (i=0;i<5;i++)
  cout<<DouAry.Entry(i)<<'/t';
 cout<<endl;
    return 0;
}

發佈了26 篇原創文章 · 獲贊 11 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章