#include <IOSTREAM>
using namespace std;
/*模板template的应用*/
template<class type> //使用模板将type定义成一个可根据实际情况被编译器自动识别并设定的数据类型
tswap(type & a, type & b)
{
type temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int x = 6, y = 8;
cout<<"交换前,x:"<<x<<" y:"<<y<<endl;
tswap(x, y);
cout<<"交换后,x:"<<x<<" y:"<<y<<endl;
float f = 12.567f, j = 93.789f;
cout.precision(12);//精度是指总共输出的有效位数(包括整数部分和小数部分).
cout<<"交换前,f:"<<f<<" j:"<<j<<endl;
tswap(f, j);
cout<<"交换后,f:"<<f<<" j:"<<j<<endl;
double g = 34.09899, k = 893.0983457;
cout<<"交换前,g:"<<g<<" k:"<<k<<endl;//浮点数精度更高,所以此处能被精确输出。
tswap(g, k);
cout<<"交换后,g:"<<g<<" k:"<<k<<endl;
return 0;
}/*
交换前,x:6 y:8
交换后,x:8 y:6
交换前,f:12.5670003891 j:93.7890014648
交换后,f:93.7890014648 j:12.5670003891
交换前,g:34.09899 k:893.0983457
交换后,g:893.0983457 k:34.09899
Press any key to continue
*/
C++模板小例
最新推荐文章于 2024-07-27 14:22:20 发布