所以我正在学习C ++,我必须创建一个重载函数,并从中获取一组数字中最大的数字。这适用于2个数字但是当我注释掉2个数字的函数调用并尝试3个数字时,它给了我很多错误。我需要一双新眼睛来看我的代码,看看我做错了什么。
#include <iostream>
using namespace std;
// function prototypes
double max(double numberOne, double numberTwo);
double max(double numberOne, double numberTwo, double numberThree);
int main()
{
int numberOne,
numberTwo,
numberThree;
// user input
cout << "Input number 1: " << endl;
cin >> numberOne;
cout << "Input number 2: " << endl;
cin >> numberTwo;
cout << "Input number 3: " << endl;
cin >> numberThree;
cout << "The largest of " << numberOne << " and " << numberTwo << ": " << max(numberOne, numberTwo) << endl;
cout << "The largest of " << numberOne << ", " << numberTwo << ", and " << numberThree << ": " << max(numberOne, numberTwo, numberThree) << endl;
return 0;
}
// function declarations
double max(double numberOne, double numberTwo) {
// if number one is greater than number two return that
// otherwise return numberTwo as the greater value
if (numberOne > numberTwo) {
return numberOne;
} else {
return numberTwo;
}
}
double max(double numberOne, double numberTwo, double numberThree) {
// compare 1 and 2 to see which is greater
if (numberOne > numberTwo) {
if (numberOne > numberThree) {
// 2 is greater return it
return numberOne;
} else {
// else 3 is greater return that
return numberThree;
}
} else {
if (numberTwo > numberThree) {
// 2 is greater return it
return numberTwo;
} else {
// else 3 is greater return that
return numberThree;
}
}
}
答案 0 :(得分:2)
using namespace std;
// function prototypes
double max( ... )
通过在此上下文中定义具有该名称的函数,您遇到与std :: max的冲突。
将max
放入自己的命名空间,不要导入std
,或两者兼而有之。作为折衷方案,您可以using
std
using std::vector;
using std::map;
using std::string;
来代替所有这些名称。像这样:
{{1}}
As an aside -- I'm floored -- it's as if I summoned this question myself very recently!
答案 1 :(得分:0)
使用::max()
代替max()
访问您的版本,因此不会与std::max()
冲突。像这样:
cout << "The largest of " << numberOne << " and " << numberTwo << ": " << ::max(numberOne, numberTwo) << endl;
cout << "The largest of " << numberOne << ", " << numberTwo << ", and " << numberThree << ": " << ::max(numberOne, numberTwo, numberThree) << endl;
但是,更优雅的解决方案是实际利用std::max()
和/或为您的功能使用不同的名称。
答案 2 :(得分:0)
问题是max不明确。
您可以重命名您的功能(类似于my_max),
或使用范围解析运算符来调用您的(全局)版本,例如。 :: MAX()