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;
}
發佈了25 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章