类模板的声明和使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类模板的声明和使用相关的知识,希望对你有一定的参考价值。
类模板是类的抽象,类是类模板的实例
在类模板内定义:
类模板名<实际类型名>对象名;
类模板名<实际类型名>对象名(实参表);
在类模板外定义成员函数:
template<class 虚拟类型参数>
函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表){...}
如:
template<class numtype>
numtype Compare<numtype>::max()
{
return(x > y) ? x : y;
}
例:声明一个类模板,利用它分别实现两个整数、浮点数和字符的比较,求出大数和小数。
程序:
#include<iostream>
using namespace std;
template<class numtype>//类模板声明,虚拟类型名为numtype
class Compare//类模板名为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;
};
int main()
{
Compare<int>cmpl(3, 7);
cout <<cmpl.max()<<" is the Maximum of two integer numbers. "<< endl;
cout << cmpl.min() << " is the Minimum of two integer numbers. " << endl<<endl;
Compare<float>cmp2(3.5, 77.1);
cout << cmp2.max() << " is the Maximum of two integer numbers. " << endl;
cout << cmp2.min() << " is the Minimum of two integer numbers. " << endl << endl;
Compare<char>cmp3(‘a‘, ‘A‘);
cout << cmp3.max() << " is the Maximum of two integer numbers. " << endl;
cout << cmp3.min() << " is the Minimum of two integer numbers. " << endl;
system("pause");
return 0;
}
结果:
7 is the Maximum of two integer numbers.
3 is the Minimum of two integer numbers.
77.1 is the Maximum of two integer numbers.
3.5 is the Minimum of two integer numbers.
a is the Maximum of two integer numbers.
A is the Minimum of two integer numbers.
请按任意键继续. . .
本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1760110
以上是关于类模板的声明和使用的主要内容,如果未能解决你的问题,请参考以下文章