'sqtr'ambiguous call to overloaded function

'sqtr'ambiguous call to overloaded function

 

引用楼主 liudafei1 的帖子:
1>f:/Project/hello.cpp(20) : error C2668: 'sqrt' : ambiguous call to overloaded function
1> D:/Microsoft Visual Studio 8/VC/include/math.h(581): could be 'long double sqrt(long double)'
1> D:/Microsoft Visual Studio 8/VC/include/math.h(533): or 'float sqrt(float)'

这涉及到C++的函数重载的概念。
当编译器看到sqrt(4)的时候,它会试图去找一个sqrt(int)的函数,但是找不到。
于是退而求其次,找一个可以从int转换过去的sqrt,结果一下找到了两个,一个是sqrt(long double),另一个是sqrt(float)。编译器认为把int转换成long double或者float都很合理,于是编译器就晕菜了,不知道程序员的真正意图到底是要用哪一个,只好停下来请示,要求程序员明确指定其中一个。
sqrt(4.0)就不存在这个问题,因为4.0不是int,编译器不需要做转换,直接用对应的就行了。

 

sqrtf(4)没问题,是因为sqrtf只有一个函数原型sqrtf(float),编译器没有任何其它选择,就很高兴的直接把int转换成float了。

如果是sqrt( 4.0 )就不会有错了,或者是用sqrtf( 4 )都行

你可能感兴趣的:(c,function,float,编译器)