C++求3个数中最大的数和3个字符串的最大字符串利用类的重载定义两个max函数利用不同参数类型和返回值类型区别实现不同功能
时间: 2024-03-10 13:47:37 浏览: 29
好的,根据你的需求,以下是使用类的重载定义两个max函数的程序实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Max {
public:
int max(int a, int b, int c) {
int maxNum = a > b ? a : b;
maxNum = maxNum > c ? maxNum : c;
return maxNum;
}
string max(string str1, string str2, string str3) {
string maxStr = str1 > str2 ? str1 : str2;
maxStr = maxStr > str3 ? maxStr : str3;
return maxStr;
}
};
int main() {
Max m;
int a = 10, b = 20, c = 30;
cout << "最大的数是:" << m.max(a, b, c) << endl;
string str1 = "hello", str2 = "world", str3 = "cpp";
cout << "最大的字符串是:" << m.max(str1, str2, str3) << endl;
return 0;
}
```
在上面的代码中,我们定义了一个名为Max的类,其中有两个max函数,一个函数接收三个整数参数,返回一个整数,另一个函数接收三个字符串参数,返回一个字符串。这两个函数的名称和参数列表不同,因此它们可以重载。在主函数中,我们创建了一个Max对象m,然后调用两个不同版本的max函数进行测试。
希望这个实现能够帮到你!