Dav*_*vid 2 c++ overloading overload-resolution
我试图使用浮动和整数重载.当我只使用整数时,代码运行正常,但是当我包含浮动时它给了我错误.代码如下:
#include <iostream>
using namespace std;
int calculate(int x,int y);
float calculate(float x,float y);
const int MAININT=4;
int main()
{
int result=calculate(5,5);
float fresult=calculate(7.5,7.5); LINE X
cout << (result + MAININT + fresult); LINE Y
return 0;
}
int calculate(int x,int y)
{
int result=x*y;
return result;
}
float calculate(float x,float y)
{
int result=x*y;
return result;
}
Run Code Online (Sandbox Code Playgroud)
通过从LINE Y删除LINE X和fresult,代码没有给我任何错误.所以我假设LINE X中肯定有问题,但我不明白为什么会出错.
我收到的错误消息是:
[Error] call of overloaded 'calculate(double, double)' is ambiguous
[Note] candidates are:
[Note] int calculate(int, int)
[Note] float calculate(float, float)
Run Code Online (Sandbox Code Playgroud)
我不明白错误消息,所以我没有包含它们.我从songyuanyao的答案中理解我做错了什么,但下次我会从一开始就在我的问题中包含错误信息,这样就可以更容易地看到我在代码中做错了什么.
son*_*yao 10
因为7.5是double(见浮点文字),不是float; 和隐式转换为int或被float视为相同的排名.
如果你7.5在float这里假设你可以使用后缀f或F使它成为float文字.例如
float fresult = calculate(7.5f, 7.5f); // 7.5f is a float literal; no ambiguity
Run Code Online (Sandbox Code Playgroud)
或使用显式转换:
float fresult = calculate(static_cast<float>(7.5), static_cast<float>(7.5));
Run Code Online (Sandbox Code Playgroud)