C++ 基础之 "模版函数","类模版"

看一些C++代码看到T符号就头痛,不知道怎么用。看了下书,记录在这里。


1.模版函数


如果要编写一个函数比较两个数并指出第一个数是小于,等于还是大于第二个数。我们可能会定义下面的函数,如果有几种类型,我们可能会定义几个重载函数。


//比较两个数,如果相同返回0,如果v1大,返回1,如果v2大,返回-1
int compare(const int &v1, const int &v2)
{
    if(v1 < v2) return -1;
	if(v2 < v1) return 1;
	return 0;
}
int compare(const double &v1, const double &v2)
{
    if(v1 < v2) return -1;
	if(v2 < v1) return 1;
	return 0;
}
这两个函数几乎相同,唯一不同的是形参的类型。

用模版函数来改写就是下面的程序:

template是一个声明模板的关键字,类型参数一般用T这样的标识符来代表一个虚拟的类型(刚开始我还因为T是关键词,T可以是任意的字符换成R,myType都可以),当使用函数模板时,会将类型参数具体化。typename和class关键字作用都是用来表示它们之后的参数是一个类型的参数。只不过class是早期C++版本中所使用的,后来为了不与类产生混淆,所以增加个关键字typename。

template <typename T>

int compare(const T &v1, const T &v2)
{
	if(v1 < v2) return -1;
	if(v2 < v1) return 1;
	return 0;
}

int main(int argc, char* argv[])
{       
        //因为我们定义了模版函数,可以轻松的更改a,b变量的类型,int,double。而不需要更改函数
double a = 1.5,b = 2.5;
printf("result:%d\n",compare(a,b));//相当于调用double compare(const double &v1,const double &v2)
int j=1,i=2;        
printf("result:%d\n",compare(j,i));//相当于调用int compare(const int &v1,const int &v2)        
return 0;
}


一个类模版例子:


#include <iostream>
using namespace std;

template <class T>
//定义类模版
class Compare
{
   public :
	   Compare(T a,T b)
	   {x=a;y=b;}
	   T max( )
	   {return (x>y)?x:y;}
	   T min( )
	   {return (x<y)?x:y;}
   private :
	   T x,y;
};
int main( )
{
	Compare<int> cmp1(3,7);//比较整数
	cout<<cmp1.max( )<< "is the Maximum of two integer numbers."<<endl;
	cout<<cmp1.min( )<<" is the Minimum of two integer numbers."<<endl<<endl;
	Compare<float> cmp2(45.78,93.6); //比较浮点数
	cout<<cmp2.max( )<<" is the Maximum of two float numbers."<<endl;
	cout<<cmp2.min( )<<" is the Minimum of two float numbers."<<endl<<endl;
	Compare<char> cmp3('a','A'); //比较字符
	cout<<cmp3.max( )<<" is the Maximum of two characters."<<endl;
	cout<<cmp3.min( )<<" is the Minimum of two characters."<<endl;
	return 0;
}



文章原页面:http://www.waitingfy.com/?p=260

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瓦力冫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值