这个问题在这里已经有了答案:
对函数的引用是不明确的[重复] 2个答案编译以下代码时:
#include <iostream> using namespace std; void print(int i){ cout << i << endl; } void print(float i){ cout << i << endl; } int main(){ print(5); print(5.5) return 0; }我收到错误:
重载“打印(双)”的调用是不明确的。
但是,如果我改变了
void print(float i){至
void print(double i){代码编译。 这是为什么?
This question already has an answer here:
Reference to function is ambiguous [duplicate] 2 answersWhen compiling the following code:
#include <iostream> using namespace std; void print(int i){ cout << i << endl; } void print(float i){ cout << i << endl; } int main(){ print(5); print(5.5) return 0; }I get the error:
call of overloaded 'print(double)' is ambiguous.
However, if I change
void print(float i){to
void print(double i){the code compiles. Why is that?
最满意答案
尝试不同的练习来理解这一点。 删除两个重载中的任何一个都会使程序编译,尽管没有字面5.5身份匹配,一个double值,它可以隐式转换为int或float 。
当两个重载都存在时,由于5.5可以隐式转换为int或float ,所以两者都是可行的。 编译器无法在两者之间做出决定,因此出现错误。
在将字面值5.5f float 5.5f ,我们有了一个身份匹配, float重载和编译器决策中没有含糊之处。 相反,保持字面值double , 5.5 ,将函数原型从float更改为double也是可行的,因为这也是一个身份匹配。
Try a different exercise to understand this. Removing either of the two overloads will make the program compile, although there's no identity match for the literal 5.5, a double value, it can be implicitly converted to int or float.
When both overloads are present, since 5.5 can be implicitly converted to either a int or float, both are viable. The compiler is unable to decide between the two, hence the error.
Upon making the literal a float, 5.5f, we've an identity match, the float overload and no ambiguity in decision for the compiler. Conversely, keeping the literal double, 5.5, changing the function prototype from float to double also works since this is an identity match as well.
更多推荐
发布评论