天天看點

c++不常用功能之——類模闆

類模闆是對類的抽象,即對類中的函數和資料進行參數化。類模闆中的成員函數為 函數模闆。

#include<iostream>              using namespace std;              //定義結構體              struct Student{              int id;              float average;              };              //類模闆              template<class T>              class Store{              public:              Store(void);              T GetElem(void);              void PutElem(T x);              private:              T item;              int haveValue;              };              //以下是成員函數的實作,主要,類模闆的成員函數都是函數模闆              template<class T>              Store<T>::Store(void) :haveValue(0){                  }              template<class T>              T Store<T>::GetElem(void){              if (haveValue == 0){              cout << "item沒有存入資料!" << endl;              exit(1);              }              return item;              }              //存入資料的函數實作              template<class T>              void Store<T>::PutElem(T x){              haveValue = 1;              item = x;              }              int main(){              //聲明Student結構體類型變量,并指派              Student g = { 103, 93 };              Store<int> S1, S2;              Store<Student> S3;                  S1.PutElem(7);              S2.PutElem(-1);              cout << S1.GetElem() << " " << S2.GetElem() << endl;              S3.PutElem(g);              cout << "The student id is " << S3.GetElem().id << endl;              return 0;              }               

繼續閱讀