C++ 编写函数模板

编写函数模板的一般方法:

(1)定义一个普通的函数,数据类型采用具体的普通的数据类型。

(2)将数据类型参数化。

(3)在函数头前用关键字template引出对类型参数名的声明。

  1. <span style="font-size:18px;">#include<iostream>  
  2. using namespace std;  
  3.   
  4. template <class T>  
  5. T min(T x, T y)  
  6. {  
  7.     if(x < y)  
  8.         return x;  
  9.     else  
  10.         return y;  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     int n1=2, n2=10;  
  16.     double d1=1.5, d2=5.6;  
  17.     cout<<"较小的整数:"<<min(n1,n2)<<endl;  
  18.     cout<<"较小的实数:"<<min(d1,d2)<<endl;  
  19.     return 0;  
  20. }</span>  

  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class MyClass  
  5. {  
  6.     int x, y;  
  7. public:  
  8.     MyClass(int x1, int y1){  
  9.         x = x1;  
  10.         y = y1;  
  11.     }  
  12.   
  13.     int getx(){return x;}  
  14.     int gety(){return y;}  
  15.     int operator<(MyClass &c){//重载运算符"<"  
  16.         if(x<c.x && y<c.y)  
  17.             return 1;  
  18.         else  
  19.             return 0;  
  20.     }  
  21. };   
  22.   
  23. template <class T> //函数模板声明  
  24. T &min(T &o1, T &o2)  
  25. {  
  26.     if(o1 < o2)  
  27.         return o1;  
  28.     else  
  29.         return o2;  
  30. }  
  31.   
  32. int main()  
  33. {  
  34.     MyClass s1(5,1);  
  35.     MyClass s2(6,18);  
  36.     MyClass s3(min(s1, s2)); //利用重载<运算符比较两个MyClass对象  
  37.     cout<<"较小的坐标:("<<s3.getx()<<","<<s3.gety()<<")"<<endl;  
  38.     double d1=3.25;  
  39.     double d2=2.54;  
  40.     cout<<"较小的数:"<<min(d1,d2)<<endl;//利用标准<运算符比较两个实数  
  41.     return 0;  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值