为什么这里有错误?
#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;
}
Run Code Online (Sandbox Code Playgroud)
构建输出:
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 ==========
Run Code Online (Sandbox Code Playgroud)
有三个重载的sqrt内搭不同的参数:float sqrt(float),double sqrt(double)和long double sqrt(long double)。您可以在编译器输出中看到这些。
如果sqrt使用整数参数(例如sqrt(9))进行调用,则可以将整数强制转换为这三种类型中的任何一种。那么应该调用哪个函数呢?编译器不知道。它是模棱两可的,因此会出现错误,迫使您明确选择所需的重载。只需将参数转换为匹配以下重载之一即可:sqrt(static_cast<float>(((a.x-b.x)*(a.x-b.x))+((a.y-b.y)*(a.y-b.y)))。
| 归档时间: |
|
| 查看次数: |
7082 次 |
| 最近记录: |