函数重载实现了让同名函数处理不同类型的数据,但最好的解决方法是类型参数化,这样就得到了函数模板。使用模板的目的就是能够让程序员编写与类型无关的代码。要求设计求两个或三个不同类型变量之最大值的函数模板,并在主函数中进行测试。 函数接口定义: template<class T> T myMax(T a,T b); template<class T> T myMax(T a,T b,T c); T是抽象类型,可以由int,double,char,string类型实例化,两个函数模板也可以进行重载。 裁判测试程
时间: 2024-03-16 08:42:07 浏览: 109
通过string转换比较好些,很多重载函数要么是char * ,要么是String
序如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
template<class T>
T myMax(T a, T b) {
return (a > b) ? a : b;
}
template<class T>
T myMax(T a, T b, T c) {
return myMax(myMax(a, b), c);
}
int main() {
int int1 = 10, int2 = 20, int3 = 30;
double double1 = 10.5, double2 = 20.5, double3 = 30.5;
char char1 = 'a', char2 = 'b', char3 = 'c';
string string1 = "hello", string2 = "world", string3 = "!";
cout << "Max of " << int1 << " and " << int2 << " is " << myMax(int1, int2) << endl;
cout << "Max of " << int1 << ", " << int2 << ", and " << int3 << " is " << myMax(int1, int2, int3) << endl;
cout << "Max of " << double1 << " and " << double2 << " is " << myMax(double1, double2) << endl;
cout << "Max of " << double1 << ", " << double2 << ", and " << double3 << " is " << myMax(double1, double2, double3) << endl;
cout << "Max of " << char1 << " and " << char2 << " is " << myMax(char1, char2) << endl;
cout << "Max of " << char1 << ", " << char2 << ", and " << char3 << " is " << myMax(char1, char2, char3) << endl;
cout << "Max of " << string1 << " and " << string2 << " is " << myMax(string1, string2) << endl;
cout << "Max of " << string1 << ", " << string2 << ", and " << string3 << " is " << myMax(string1, string2, string3) << endl;
return 0;
}
```
输出结果如下:
```
Max of 10 and 20 is 20
Max of 10, 20, and 30 is 30
Max of 10.5 and 20.5 is 20.5
Max of 10.5, 20.5, and 30.5 is 30.5
Max of a and b is b
Max of a, b, and c is c
Max of hello and world is world
Max of hello, world, and ! is world
```
阅读全文