模板(template)
类模板的例子:
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;
};
Compare 是类模板名,不是具体的类,类模板中的类型numtype并不是一个实际的类型,而是一个虚拟的类型,无法用它去定义对象。必须用实际类型名去取代虚拟的类型。
类模板相当于抽象的对象,并不占内存空间,需要实例化才可以使用。
具体做法:
Compare<int> cmp(4,7);
此处int可以换成 double/float/char,当然,改动后cmp函数内的值也需要改动。