1.模板使类的成员为一个可变的参数
template <模板的形式参数表> class类名 {...}
#include <iostream> using namespace std; template<class T> class Array { int low; int high; T *storage; public: Array(int lh=0,int rh=0):low(lh),high(rh) { storage=new T[high-low+1];// } Array(const Array &arr); Array &operator=(const Array &a); T &operator[](int index); ~Array(){if(storage) delete []storage;} }; template <class T> Array<T>::Array(const Array<T> &arr)//不指明返回值类型 { low=arr.low; high=arr.high; storage=new T[high-low+1]; for(int i=0;i<high-low+1;i++) storage[i]=arr.storage[i]; } template <class T> Array<T> &Array<T>::operator=(const Array &other) { if(this==&other) return *this; delete []storage; low=other.low; high=other.high; storage=new T[high-low+1]; for(int i=0;i<high-low+1;i++) storage[i]=other.storage[i]; return *this; } template <class T> T &Array<T>::operator[](int index) { if(index<low||index>high) { cout<<"下标越界"; } return storage[index-low]; } int main() { Array<int> array1(20,30);//类模板的实例化Array<int> for(int i=20;i<30;i++) cout<<array1[i]<<endl; }
//模板类 #include<iostream> using namespace std; template <class T> class B { private: T x; public: T f(T x) {return x;} }; int main() { B<char> b; cout<<b.f('c'); }
3.类模板的定义和实现都应在.h文件