gpt4 book ai didi

c++ - g++ 错误 : call of overloaded 'abs(unsigned int)' is ambiguous

转载 作者:行者123 更新时间:2023-11-30 00:44:07 30 4
gpt4 key购买 nike

我正在尝试编译以下代码:

#include <stdlib.h>
static
unsigned iSqr( unsigned i )
{
unsigned res1 = 2;
unsigned res2 = i/res1;
while( abs( res1 - res2 ) > 1 )
{
res1 = (res1 + res2)/2;
res2 = i/res1;
}
return res1 < res2 ? res1 : res2;
}

使用 g++ test.cc -o test

但是,g++ 编译器失败并出现以下错误:

test.cc: In function 'unsigned int iSqr(unsigned int)':                                         
test.cc:8:29: error: call of overloaded 'abs(unsigned int)' is ambiguous
while( abs( res1 - res2 ) > 1 )
^
In file included from /usr/include/c++/6/cstdlib:75:0,
from /usr/include/c++/6/stdlib.h:36,
from test.cc:2:
/usr/include/stdlib.h:735:12: note: candidate: int abs(int)
extern int abs (int __x) __THROW __attribute__ ((__const__)) __wur;
^~~
In file included from /usr/include/c++/6/stdlib.h:36:0,
from test.cc:2:
/usr/include/c++/6/cstdlib:185:3: note: candidate: __int128 std::abs(__int128)
abs(__GLIBCXX_TYPE_INT_N_0 __x) { return __x >= 0 ? __x : -__x; }
^~~
/usr/include/c++/6/cstdlib:180:3: note: candidate: long long int std::abs(long long int)
abs(long long __x) { return __builtin_llabs (__x); }
^~~
/usr/include/c++/6/cstdlib:172:3: note: candidate: long int std::abs(long int)
abs(long __i) { return __builtin_labs(__i); }
^~~

为什么会发生此错误以及如何解决?

g++版本为:gcc版本6.3.0

最佳答案

abs<stdlib.h> (自 c++11 起):http://www.cplusplus.com/reference/cstdlib/abs/

          int abs (          int n);
long int abs ( long int n);
long long int abs (long long int n);

如果过载,调用将不明确分辨率 无法选择比此类不可微函数更好的调用匹配项。

您可以像这样显式地转换参数:

static_cast<int>(res1 - res2)

关于c++ - g++ 错误 : call of overloaded 'abs(unsigned int)' is ambiguous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301469/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com