C++函数模板学习笔记

函数的模板:不知道函数模板是什么意思看,看了模板二字基本知道函数模板了,估计也就是一函数重复使用意思,只是传不同类似的参数然后返回对应类型的数据。

函数模板定义的形式:template<class T>或template <typenameT>

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

int main(int argc, char** argv) {
	cout <<max(2,5)<<"\t"<<max(2.0,5.0)<<"\t"<<max('w','a')<<"\t"<<max("ABC","ABD")<<endl;
	return 0;
}
template <class T>
T max(T m1,T m2)
{
	return(m1>m2)?m1:m2;
}
//第二个例子

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
template <typename T>
void Swap(T &a,T &b);

int main(int argc, char** argv) {
	int i = 10;
	int j = 20;
	cout <<"i,j=="<<i<<","<<j<<".\n";
	Swap(i,j);
	cout <<"i,j=="<<i<<","<<j<<".\n";
	return 0;
}

template <typename T>
void Swap(T &a,T &b)
{
	T temp;
	temp=a;
	a=b;
	b=temp;
}


以上例子中第一个例子有点问题,今天测试中发现第一个例子没有申明自己的模板,直接定义模板了但是编译的时候不会报错也能顺利通过,但是其他模板不声明就不能编译通过,最后发现自己的max函数和标准库的max重名了,调用的时候调用的是标准库中的函数,所以能顺利编译通过以下是我改名后我的函数,需要添加声明的,所以在第一个例子的基础上修改一下贴出来以后留着查看

正确的例子:

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
//添加声明
template <class Person>
Person comparMax(Person m1,Person m2);
int main(int argc, char** argv) {
	cout <<comparMax(2,5)<<"\t"<<comparMax(2.0,5.0)<<"\t"<<comparMax('w','a')<<"\t"<<comparMax("ABC","ABD")<<endl;
	return 0;
}

template <class Person>
Person comparMax(Person m1,Person m2)
{
	return(m1>m2)?m1:m2;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值