如题
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/*************program***********/
template <class type1>type1 MyMax(type1 a,type1 b)
{
if(a>b)
{
return a;
}
else
{
return b;
}
}
/*************end**************/
int main(int argc,char* argv[])
{
int a=10,b=20;
cout<<"更大的整数:"<<MyMax<int>(a,b)<<endl;
double c=3.14,d=1.56;
cout<<"更大的数:"<<MyMax<double>(c,d)<<endl;
char ch1='A',ch2='C';
cout<<"更大的字符:"<<MyMax(ch1,ch2)<<endl;
string s1="abc",s2("abc");
cout<<"更大的字符串对象:"<<MyMax<string>(s1,s2)<<endl;
}
本文介绍了一个通用的模板函数,用于比较两个参数并返回较大的一个。该函数使用了C++模板特性,能够处理不同类型的输入,包括整数、浮点数、字符和字符串等。通过实例展示了如何调用此函数进行类型安全的最大值比较。

被折叠的 条评论
为什么被折叠?



