当前位置: 首页 > 工具软件 > CppTest > 使用案例 >

cppTest-3.5:模板函数

蒲德曜
2023-12-01
/**
 *cppTest-3.5:模板函数
 *
 *author 炜sama
 */
#include<iostream.h>
#include<conio.h>
#include<string.h>

template<class Type>//说明Type是一个类型,在接下来的代码中将会使用这个类型
//int i=0;//测试发现这里不能插入任何代码!!
Type max(Type v1,Type v2)//使用上面定义的类型来定义函数
{
    return v1>v2?v1:v2;
}

char *max(char *x,char *y)//(1)与上面的模板函数同名的一般函数,调用的顺序是一般函数优先!
{
    return strcmp(x,y)>0?x:y;
}

template<class T>
void div(T v1,T v2){
	cout<<"v1:"<<v1<<",v2:"<<v2<<",v1/v2:"<<v1/v2<<endl;
}

void main()
{
	int m1=max(100,300);
    double m2=max(32.1,3.14);
    char *m3=max("Zhang", "Li");
    cout<<"The maxium of 100 and 300 is:"<<m1<<endl;
    cout<<"The maxium of 32.1 and 3.14 is:"<<m2<<endl;
    cout<<"The maxium of Zhang and Li is:"<<m3<<endl;//如果没有上面的(1),这里返回的结果是错的!
    
	div(5.0,2.0);//第一个参数5.0把T实例化为double型,那第二个参数也必须是double型,否则报错。例如为2,2不会自动转型为double!报错!
	//div(5,2.0);//报错!
	//div(5.0,2);//报错!
	div(5.0f,2.0f);
	//div(5.0,2.0f);//报错!
	//div(5.0f,2.0);//报错!
	div(1,1);
	div(5,2);
}

 类似资料: