对于类来说,如果有多各类的成员具有相似的形式,只是诸如数据类型不同,则可以考虑使用类的模板。
可以声明一个通用的模板类,它可以有一个或多个虚拟的模拟参数:
- template <class 类型参数名>//声明模板类
- class 具体类型参数名 //定义具体类
- {
- //...
- }
下面是一个具体的实例:
- template <class numtype> //声明时要添加一行template<class numtype>
- class Compare
- {
- public :
- Compare(numtype a,numtype b)
- {
- x=a;
- y=b;
- }
- numtype max()
- {
- return (x>y)?x:y;
- }
- numtype min()
- {
- return (x<y)?x:y;
- }
- private :
- numtype x,y;
- } //原有的类型名都改为numtype
而在使用的时候,要在尖括号里面添加具体的类型名:
- Compare<double> cmp(2.3, 5.8);
在类的外面定义某个函数的时候:
template <class t>
t compare<t>::max()
{
}
本文转自:http://blog.chinaunix.net/uid-27177626-id-3939006.html