问题描述
为什么这里有错误?
#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)
和 long double sqrt(long double)
.您可以在编译器输出中看到它们.
There are three overloads of sqrt
which take different parameters: float sqrt(float)
, double sqrt(double)
and long double sqrt(long double)
. You can see these in the compiler output.
如果您使用整数参数(例如 sqrt(9)
)调用 sqrt
,则可以将整数强制转换为这三种类型的 any .那么应该调用哪个函数呢?编译器不知道.它是模棱两可的,因此会出现错误,迫使您明确选择所需的重载.只需将参数强制转换为匹配这样的重载之一即可: sqrt(static_cast< float>((((ax-bx)*(ax-bx))+((ay-by)*(ay-by)))
.
If you call sqrt
with an integer parameter, like sqrt(9)
, an integer can be cast to any of those three types. So which function should be called? The compiler doesn't know. It's ambiguous, so you get an error to force you to explicitly choose the overload you want. Just cast the parameter to match one of the overloads like this: sqrt(static_cast<float>(((a.x-b.x)*(a.x-b.x))+((a.y-b.y)*(a.y-b.y)))
.
这篇关于C ++中的sqlt问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!