具有参数计算错误的重载函数
overloaded function with argument evaluation error
所以我正在学习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;
}
}
}
using namespace std;
// function prototypes
double max( ... )
通过在此上下文中定义具有该名称的函数,您遇到了与 std::max 的冲突。
要么将max
放入其自己的命名空间中,要么不要导入std
,或者两者兼而有之。 作为折衷方案,您可以从std
而不是所有名称中using
所需的单个名称。 这样:
using std::vector;
using std::map;
using std::string;
顺便说一句,我感到震惊 - 好像我最近自己提出了这个问题!
使用::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()
和/或为您的函数使用不同的名称。
问题是max是模棱两可的。
你可以重命名你的函数(像my_max这样),
或使用范围解析运算符调用您的(全局)版本,例如::max()
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 可以打印矢量和矢量中的矢量的非重载C++函数
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 使用模板重载函数
- C++线程中,没有重载函数接受 X 参数
- std::vector 没有重载函数的实例与参数列表匹配
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- 对重载函数find_first_not_of的不明确调用
- 如何从重载解析中删除重载函数?
- CUDA:重载函数"isnan"的多个实例
- C++派生类重载函数(带有 std::function 参数)不可见
- 避免在人为的重载函数调用中拼写出类型
- C++:如何为多个重载函数保留通用代码路径?
- 什么时候可以使用常量装饰调用我的重载函数?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- std::调用,未找到匹配的重载函数
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 为什么使用不匹配的参数调用重载函数仍然有效
- 如何通过签名作为模板参数来解决重载函数?