传递 size_t 时对重载 sqrt 函数的不明确调用
string aux;
int maxy, auxx = 0;
cin >> aux;
maxy = (int)sqrt(aux.size());
为什么我会收到此错误:
1> error C2668: 'sqrt' : ambiguous call to overloaded function
1> could be 'long double sqrt(long double)'
1> or 'float sqrt(float)'
1> or 'double sqrt(double)'
string aux;
int maxy, auxx = 0;
cin >> aux;
maxy = (int)sqrt(aux.size());
Why am I getting this error:
1> error C2668: 'sqrt' : ambiguous call to overloaded function
1> could be 'long double sqrt(long double)'
1> or 'float sqrt(float)'
1> or 'double sqrt(double)'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
string::size()
返回size_t
,而sqrt
在其任何版本中都不接受它。所以编译器必须进行强制转换,并且不能选择什么 - 所有这些都可以。你必须显式强制转换:string::size()
returnssize_t
, andsqrt
doesn't accept it in any of its versions. So the compiler has to cast, and cannot choose to what - all of them are OK. You have to put explicit cast:问题是,在 C++ 中,存在三个名为
sqrt
的函数 - 一个接受float
,一个接受double
,一个接受double
长双精度
。当您尝试调用时,编译器会尝试确定您要调用这些函数中的哪一个。由于
aux.size()
返回一个string::size_type
,它既不是float
、double
,也不是long double
,它尝试查看string::size_type
是否可以隐式转换为这三个中的任何一个。但由于 string::size_type 可以转换为所有这三种类型,因此编译器将调用标记为不明确,因为不清楚您想要执行哪种转换。要解决此问题,您可以将 aux.size() 显式转换为您想要的类型。例如:
or
这使得调用明确匹配两个函数之一。根据您想要的精度,您可以选择三种重载中的任何一种。由于您只是转换回
int
,因此在这里转换为float
可能没问题。The problem is that in C++, there are three functions named
sqrt
- one taking in afloat
, one taking adouble
, and one taking along double
. When you try callingThe compiler tries to determine which of these functions you want to call. Since
aux.size()
returns astring::size_type
, which is neither afloat
,double
, norlong double
, it tries to see ifstring::size_type
is implicitly convertible to any of these three. But sincestring::size_type
is convertible to all three of these types, the compiler marks the call as ambiguous, since it's unclear which of the conversions you want to do.To fix this, you can explicitly cast
aux.size()
to the type that you want. For example:or
This makes the call unambiguously match one of the two functions. Depending on the precision you want, you can choose any of the three overloads. Since you're just casting back to an
int
, it's probably fine to cast to afloat
here.aux.size()
返回std::size_t
,但sqrt()
没有采用std 的重载版本::size_t 参数。
编译器报告
sqrt
有 3 个重载:采用float
、double
和long double
参数。std::size_t
可以转换为其中任何一个,因此存在歧义,因为编译器不知道是否将std::size_t
转换为float< /code> 或
double
或long double
。aux.size()
returns anstd::size_t
, butsqrt()
does not have an overloaded version that takes astd::size_t
argument.The compiler reports that
sqrt
has 3 overloads: which takefloat
,double
andlong double
arguments.std::size_t
could be converted to any of those, so there's an ambiguity since the compiler doesn't know whether to convertstd::size_t
tofloat
ordouble
orlong double
.尝试将 aux.size() 转换为其中一种类型,这样它就不会含糊不清......
Try casting your aux.size() to one of those types, so it won't be ambiguous...