编写重载函数可求取2个整数,3个整数的最大值
时间: 2024-05-07 12:19:38 浏览: 101
2021.3.15.c++实验一.doc
下面给出两种方案:
方案一:使用函数重载实现
```c++
#include <iostream>
using namespace std;
int max(int a, int b) {
return (a > b) ? a : b;
}
int max(int a, int b, int c) {
int max1 = max(a, b);
int max2 = max(max1, c);
return max2;
}
int main() {
int a = 1, b = 2, c = 3;
cout << "max(a,b) = " << max(a, b) << endl;
cout << "max(a,b,c) = " << max(a, b, c) << endl;
return 0;
}
```
方案二:使用可变参数模板实现
```c++
#include <iostream>
#include <cstdarg>
using namespace std;
int max(int count, ...) {
int res = INT_MIN;
va_list vl;
va_start(vl, count);
for (int i = 0; i < count; ++i) {
int val = va_arg(vl, int);
res = (val > res) ? val : res;
}
va_end(vl);
return res;
}
int main() {
int a = 1, b = 2, c = 3;
cout << "max(a,b) = " << max(2, a, b) << endl;
cout << "max(a,b,c) = " << max(3, a, b, c) << endl;
return 0;
}
```
这两种方案都可以用来求取2个整数和3个整数的最大值,使用哪种方案取决于具体的需求情况。
阅读全文