一、函数模板
二、类模板
直接上示例
类模板示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| template<class T> class Store{ private: T item; bool haveValue; public: T &getElem(); void putElem(const T& x); Store(); };
template<class T> Store<T>::Store():haveValue(false){ }
template<class T> T& Store<T>::getElem(){ if(!haveValue){ cout<<"no data!"<<endl; exit(1); } return item; }
template<class T> void Store<T>::putElem(const T& x){ item = x; haveValue = true; }
struct student{ int id; float gpa; }; int main(){ Store<int>s1; s1.putElem(4); cout<<s1.getElem()<<endl; student s= {1001,98.2}; Store<student> s2; s2.putElem(s); cout<<s2.getElem().id<<" "<<s2.getElem().gpa<<endl; }
|
三、自定义动态数组类模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| template <class T> class Array { private: T *list; int size; public: Array(int sz = 50); Array(const Array<T> &a); ~Array(); Array<T> &operator=(const Array<T> &rhs); T &operator[](int i); const T &operator[](int i) const; operator T *(); operator const T *() const; int getSize() const; void reSize(int sz); };
template <class T> Array<T>::Array(int sz) { assert(sz >= 0); size = sz; list = new T[size]; }
template <class T> Array<T>::Array(const Array<T> &a) { size = a.size; list = new T[size]; for (int i = 0; i < size; i++) list[i] = a.list[i]; }
template <class T> Array<T>::~Array() { delete[] list; }
template <class T> Array<T> &Array<T>::operator=(const Array<T> &rhs) { if (this != &rhs) { if (size != rhs.size) { delete[] list; size = rhs.size; list = new T[size]; } for (int i = 0; i < size; i++) list[i] = rhs.list[i]; } return *this; }
template <class T> T &Array<T>::operator[](int i) { assert(i >= 0 && i < size); return list[i]; }
template <class T> const T &Array<T>::operator[](int i) const { assert(i >= 0 && i < size); return list[i]; }
template <class T> Array<T>::operator T *() { return list; }
template <class T> Array<T>::operator const T *() const { return list; } template <class T> int Array<T>::getSize() const { return size; } template <class T> void Array<T>::reSize(int sz) { assert(sz >= 0); if (sz == size) return; T *newlist = new T[sz]; int n = (sz < size ? sz : size); for (int i = 0; i < n; i++) newlist[i] = list[i]; delete[] list; list = newlist; size = sz; }
|
其中 operator T * ();
重载隐式转换的作用