c++之重载函数和函数模板

#include<iostream>
using namespace std;

int max_(int a,int b){
	return (a>b?a:b);
}
double max_(double a,double b){
	return (a>b?a:b);
}
long max_(long a,long b){
	return (a>b?a:b);
}

int main(){
	int a=1,b=0; 
	cout<<max_(a,b);
	
	double a_=2,b_=0; 
	cout<<max_(a_,b_);
	
	long A=3,B=0; 
	cout<<max_(A,B);
	return 0;
} 

在这里插入图片描述

//函数模板的定义语法:
//template<模板形参表>返回类型 函数名(形参列表){
//	函数体 
//} 
#include<iostream>
using namespace std;
template<typename T>
T abs(T x){
	return x<0?-x:x;
}
int main(){
	int a=1;
	double b=-1;
	cout<<abs(a)<<' '<<abs(b);
	return 0;
} 

在这里插入图片描述

#include<iostream>
using namespace std;
template<class T>
T add(T a,T b){
	return a+b;
}
int main(){
	cout<<add(1,2)<<endl;//生成整形版本的add函数 
	cout<<add(1.0,23.2)<<endl;//生成实数版本的add函数
	cout<<add('1','0')<<endl;//生成字符型版本的add函数
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值