多个类有着共同操作,但是数据类型不同。如下的3个类,getMax的功能是相同的,即求两个数中的最大值,仅仅是数据类型不同。
class Compare_int
{
private:
int x,y;
public:
Compare(int a,int b)
{
x=a;
y=b;
}
int getMax()
{
return (x>y)? x:y;
}
};
class Compare_float
{
private:
float x,y;
public:
Compare(float a,float b)
{
x=a;
y=b;
}
float getMax()
{
return (x>y)? x:y;
}
};
class Compare_char
{
private:
char x,y;
public:
Compare(char a,char b)
{
x=a;
y=b;
}
char getMax()
{
return (x>y)? x:y;
}
};
我们用一个类模板减少重复性的工作。
template<class dataType>
class Compare
{
private:
dataType x,y;
public:
Compare(dataType a,dataType b)
{
x=a;
y=b;
}
dataType getMax()
{
return (x>y)? x:y;
}
};
template是声明各模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个。
声明类模板要增加一行:
template<class 类型参数名>
如template<class dataType>其中的类型参数名为虚拟的类型参数名,以后会被实际的类型名替代。如例子中的
dataType将会被int,float,char等替代。
如果说类是对象的抽象,对象是类的实例。那么类模板是类的抽象,类是类模板的实例。
实例化时必须用实际的类型名去替代虚拟的类型,如Compare<int> cmp1(3,7);
完整的代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
template<class dataType>
class Compare
{
private:
dataType x,y;
public:
Compare(dataType a,dataType b)
{
x=a;
y=b;
}
dataType getMax()
{
return (x>y)? x:y;
}
};
int main(int argc, char* argv[])
{
//类模板的实例化(To 类)and类的实例化(To 对象)
Compare<int> cmp1(3,7);
cout<<cmp1.getMax()<<" is the Maximum of two Integer numbers"<<endl;
Compare<float> cmp2(12.3,23.4);
cout<<cmp2.getMax()<<" is the Maximun of two Float numbers"<<endl;
Compare<char> cmp3('a','b');
cout<<cmp3.getMax()<<" is the Maximun of two Char numbers"<<endl;
return 0;
}