如何修复 C/C++ 错误: call of overloaded 'abs(uint32_t)' is ambiguous
问题:
你正在尝试编译 C/C++ 程序,但你看到类似这样的错误消息
compiler-error.txt
src\main.cpp:127:21: error: call of overloaded 'abs(uint32_t)' is ambiguous指的是类似这样的行
timedelta-example.c
long timedelta = abs(millis() - startTime);解决方案
将 abs() 的参数转换为 int 或其他合适的类型:
timedelta-fixed.c
long timedelta = abs(((int)millis() - startTime));这应该修复错误。
错误消息的原因是 millis() 和 startTime 都是无符号整数(uint32_t),因此它们的差(millis() - startTime)也是 uint32_t。然而计算无符号整数的 abs() 没有意义,因为无符号整数的绝对值始终与输入参数相同。
然后,编译器尝试将 uint32_t 转换为与 abs() 兼容的任何类型,如 int、float、double… 但它不知道应该转换为哪种类型。
通过说 call of overloaded abs(),编译器试图告诉你有多种参数类型可以调用 abs(),包括 int、float、double… - 具有相同名称但不同参数类型的函数称为重载。
通过说 is ambiguous,编译器告诉你它不知道应该调用 abs() 的哪个变体。
注意编译器不知道 abs() 的所有重载变体基本上做相同的事情,所以它不会将你的 uint32_t 转换为任意类型。此外,abs() 变体的工作方式有细微差别 - 例如,float abs(float) 与 double abs(double) 的计算不同,因为它使用 32 位浮点数(float)而不是 64 位浮点数(double)计算。
因此,编译器不能假设它们都相同且调用哪个都无所谓,即使它们代表相同的底层数学操作
Check out similar posts by category:
C/C++, GCC Errors
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow