標籤:
代碼如下:
#include <iostream>#include <cstdlib>using namespace std;typedef struct Tstudent //結構體完整定義{ int nId; float fGpa;}Tstudent;template <class T> //模版類class CStroe{public: CStroe(); //建構函式 T &getElem(); // 返回引用 void putElem(const T &x); //傳遞類型引用private: T item; //資料 bool haveValue; //控制};template<class T> CStroe<T>::CStroe():haveValue(false){}//建構函式初始化template<class T> T& CStroe<T>::getElem() // 返回引用{ ////控制開關狀態 if(!haveValue) { cout<<"No item present!"<<endl; //exit(1); } return item;}template<class T> void CStroe<T>::putElem(const T &TRec) //引用(別名)傳遞{ haveValue=true; //設定開關狀態 item =TRec; //}int main(){ //整形例 CStroe<int> nStu1,nStu2; //模版類 nStu1.putElem(3); nStu2.putElem(-7); cout<<nStu1.getElem()<<""<<nStu2.getElem()<<endl; //結構類型例 Tstudent tG={1000,23}; //結構體 CStroe<Tstudent> tS3; //模版類 tS3.putElem(tG); cout<<"The student ID is "<<tS3.getElem().nId<<"\t"<<"Gpa is"<<tS3.getElem().fGpa<< endl; //Double類型 CStroe<double> dStu; cout<<"Retrieving object d..."; cout<<dStu.getElem()<<endl; getchar(); return 0;}
結果:
CFree5值分析:
附註:程式碼片段中exit(1);可用來表示程式終止的原因,可以被作業系統接收
分析結論:使用類模板使用者可以為類定義一種模式,使類中的某些資料,函數成員的參數,傳回值或局部變數能取任意類型。
C++類模板