C++中函数的重载与浮点

虽然多态是C++中一种非常有用的现象,但有时也会相当复杂。例如,考虑下面的代码片段:

null

#include<iostream>
using namespace std;
void test( float s, float t)
{
cout << "Function with float called " ;
}
void test( int s, int t)
{
cout << "Function with int called " ;
}
int main()
{
test(3.5, 5.6);
return 0;
}


在main()中调用函数test可能会导致输出“function with float called”,但代码给出以下错误:

In function 'int main()':
13:13: error: call of overloaded 'test(double, double)' is ambiguous
 test(3.5,5.6);

这是一个众所周知的事实 函数得载 ,编译器决定在重载函数中调用哪个函数。如果编译器不能在两个或多个重载函数中选择一个函数,则情况是—— 模棱两可 在函数重载中”。

  • 上述代码中的歧义背后的原因是浮动文字 3.5 5.6 编译器实际上将其视为双精度。 按照C++标准,浮点文字(编译时常数)除非用后缀明确指定(如C++ 2.2.4标准),否则被视为双。 在这里 ) 。因为编译器找不到具有双参数的函数,并且搞不清楚该值是应该从double转换为int还是float。

纠正错误: 通过提供 后缀f .

请看以下代码:

#include<iostream>
using namespace std;
void test( float s, float t)
{
cout << "Function with float called " ;
}
void test( int s, int t)
{
cout << "Function with int called " ;
}
int main()
{
test(3.5f, 5.6f); // Added suffix "f" to both values to
// tell compiler, it's a float value
return 0;
}


输出:

Function with float called

本文由 Aakash Sachdeva。 如果你喜欢Geeksforgek,并想贡献自己的力量,你也可以写一篇文章,然后把你的文章发到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享