为什么这里会出现错误呢?
#include <iostream>
#include <math.h>
#include <vector>
#include <ostream>
using namespace std;
struct Point {
int x,y;
};
int distance (const Point& a,const Point& b){
int k= sqrt(((a.x-b.x)*(a.x-b.x))+((a.y-b.y)*(a.y-b.y)));
}
int main(){
return 0;
}
构建输出:
1>------ Build started: Project: distance, Configuration: Debug Win32 ------
1> distance.cpp
1>d:\...\distance.cpp(13): error C2668: 'sqrt' : ambiguous call to overloaded function
1> c:\...\vc\include\math.h(589): could be 'long double sqrt(long double)'
1> c:\...\vc\include\math.h(541): or 'float sqrt(float)'
1> c:\...\vc\include\math.h(127): or 'double sqrt(double)'
1> while trying to match the argument list '(const int)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
共有三种重载sqrt
它采用不同的参数:float sqrt(float)
, double sqrt(double)
and long double sqrt(long double)
。您可以在编译器输出中看到这些。
如果你打电话sqrt
带有整数参数,例如sqrt(9)
,一个整数可以转换为any这三种类型中。那么应该调用哪个函数呢?编译器不知道。它是不明确的,因此您会收到一个错误,迫使您显式选择所需的重载。只需将参数转换为匹配重载之一,如下所示:sqrt(static_cast<float>(((a.x-b.x)*(a.x-b.x))+((a.y-b.y)*(a.y-b.y)))
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)