用浮点数字调用重载函数会产生'ambiguos'错误[复制](Calling overloaded function with floating point literal yie

编程入门 行业动态 更新时间:2024-10-28 08:19:53
浮点数字调用重载函数会产生'ambiguos'错误[复制](Calling overloaded function with floating point literal yields 'ambiguos' error [duplicate])

这个问题在这里已经有了答案:

对函数的引用是不明确的[重复] 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 answers

When 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.

更多推荐

本文发布于:2023-08-01 05:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1354307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   函数   错误   数字   Calling

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!