编写一个任意类类型AnyType模板求三个数的最大值,并请编写一个程序来使用该AnyType类模板。要求用整数、实数和字符来进行测试。
时间: 2024-05-13 19:18:07 浏览: 281
C语言程序设计-编写自定义函数max,用来求三个数的最大值(要求:数据的输入、输出在主函数中实现)。
5星 · 资源好评率100%
以下是实现AnyType模板的代码:
```c++
#include <iostream>
using namespace std;
template<typename AnyType>
AnyType max(AnyType a, AnyType b, AnyType c) {
AnyType maxVal = a;
if (b > maxVal) {
maxVal = b;
}
if (c > maxVal) {
maxVal = c;
}
return maxVal;
}
int main() {
int x = 5, y = 10, z = 3;
cout << "Max of " << x << ", " << y << ", " << z << " is " << max(x, y, z) << endl;
double a = 3.14, b = 2.718, c = 1.618;
cout << "Max of " << a << ", " << b << ", " << c << " is " << max(a, b, c) << endl;
char p = 'a', q = 'A', r = '!';
cout << "Max of " << p << ", " << q << ", " << r << " is " << max(p, q, r) << endl;
return 0;
}
```
输出:
```
Max of 5, 10, 3 is 10
Max of 3.14, 2.718, 1.618 is 3.14
Max of a, A, ! is a
```
可以看出,AnyType模板可以处理不同类型的数据,并正确返回最大值。
阅读全文