📄 p101 函数模板.cpp
字号:
#include<iostream>
using namespace std;
template <typename t >
t max(t a,t b,t c)
{ if(a<b) a=b;
if(a <c) a=c;
return a;
}
int main()
{
cout<<"please input three numbers: "<<endl;
float a,b,c;
cin>>a>>b>>c;
cout<<"max= " << max(a,b,c);
system("pause");
return 0;
}
/* 书上的例子是:
template <typename T>
T max(T a,T b,T c)
{ if(a<b) a=b;
if(a<c) a=c;
return a;
}
int main()
{ double a=123,b=345,c=456,d;
d=max(a,b,c);
cout<<d;
return 0;
}
李启磊:
首先,一般数据的比较都是在同种类型之间进行,编程 的时候,很忌讳对不同类型之间的数据进行比较,这样可能造成灾难性的后果;
其次,函数模板的编译,是在编译器到达使用函数模板地方的时候,才确定模板参数,然后编译的,它必须要对每个模板参数的大小类型完全知晓,并且不能混淆才能通过编译(类型混乱了,电脑可分不清~)。
第三,计算所做的事情,都是确定的指令。用户可能做出的选择,要完全由程序员去提前考虑,去实现,而不是由电脑去思考……
第四,函数模板的使用,并非是动态的,而是在编译的时候就确定类型的,也就是说,你在需要使用函数模板的地方,就必须把需要的类型参数都明确传递进去,才能通过编译
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -