Part9 模板與群體數據 9.1模板
阿新 • • 發佈:2017-12-26
定義 i++ ret space 9.1 get ++ ostream blog
1函數模板
函數模板定義語法
template <模板參數表>
模板參數表的內容
類型參數:class(或typename) 標識符
常量參數:類型說明符 標識符
模板參數:template <參數表> class標識符
//例:求絕對值函數的模板 #include<iostream> using namespace std; template<typename T> T abs(T x){ return x < 0 ? -x : x; } int main(){ int n = -5; double d = -5.5; cout << abs(n) << endl; cout << abs(d) << endl; return 0; }
//9-1函數模板的示例 #include<iostream> using namespace std; template<class T> void outputArray(const T *array, int count){ for(int i = 0; i < count;i++) cout << array[i] << ""; cout << endl; } int main(){ const int A_COUNT = 8, B_COUNT = 8, C_COUNT = 20; int a[A_COUNT] = {1,2,3,4,5,6,7,8}; double b[B_COUNT] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8}; char c[C_COUNT] = "Welcome!"; cout << "a array contains: " << endl; outputArray(a, A_COUNT); cout<< "b array contains: " << endl; outputArray(b, B_COUNT); cout << "c array contains: " << endl; outputArray(c, C_COUNT); return 0; }
2類模板
//例9-2 類模板示例 #include<iostream> #include<cstdlib> using namespace std; struct Student{ int id; float gpa; }; template<class T> class Store{//類模板:實現對任意類型數據進行存取 private: T item; bool haveValue; public: Store(); T &getElem();//提取數據函數 void putElem(const T &x);//存入數據函數 }; template<class T> Store<T>::Store():haveValue(false){} template<class T> T &Store<T>::getElem(){ //如果試圖提取未初始化的數據,則終止程序 if(!haveValue){ cout << "No item present!" << endl; exit(1); //使程序完全退出,返回到操作系統 } return item; } template<class T> void Store<T>::putElem(const T &x){ haveValue = true; item = x; } int main(){ Store<int> s1, s2; s1.putElem(3); s2.putElem(-7); cout << s1.getElem() << " " << s2.getElem() << endl; Student g = {1000,23}; Store<Student> s3; s3.putElem(g); cout << "The student id is " << s3.getElem().id << endl; Store<double> d; cout << "Retrieving object D..."; cout << d.getElem() << endl;//d未初始化 return 0; }
Part9 模板與群體數據 9.1模板