编写一个任意类类型AnyType模板求三个数的最大值,并请编写一个程序来使用该AnyType类模板。要求用整数、实数和字符来进行测试。
时间: 2024-02-29 16:52:57 浏览: 188
好的,我来为您编写该任意类类型模板:
```c++
#include <iostream>
#include <cstring>
template<typename AnyType>
AnyType Max(AnyType a, AnyType b, AnyType c) {
AnyType max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
return max;
}
int main() {
int a = 10, b = 20, c = 30;
double d = 10.5, e = 20.5, f = 30.5;
char g[] = "abc", h[] = "def", i[] = "ghi";
std::cout << "Max of " << a << ", " << b << ", " << c << " is " << Max(a, b, c) << std::endl;
std::cout << "Max of " << d << ", " << e << ", " << f << " is " << Max(d, e, f) << std::endl;
std::cout << "Max of " << g << ", " << h << ", " << i << " is " << Max(g, h, i) << std::endl;
return 0;
}
```
输出结果如下:
```
Max of 10, 20, 30 is 30
Max of 10.5, 20.5, 30.5 is 30.5
Max of abc, def, ghi is ghi
```
可以看到,我们成功地使用了该AnyType类模板,并且可以对整数、实数和字符进行测试。
阅读全文