【发布时间】:2013-03-05 07:17:04
【问题描述】:
我需要使用 cmath 的 abs() 函数,但 Visual Studio 说它超载了,我什至不能使用这样的东西:
unsigned a = 5, b = 10, c;
c = abs(a-b);
我不知道如何正确使用它。
【问题讨论】:
标签: c++ math overloading
我需要使用 cmath 的 abs() 函数,但 Visual Studio 说它超载了,我什至不能使用这样的东西:
unsigned a = 5, b = 10, c;
c = abs(a-b);
我不知道如何正确使用它。
【问题讨论】:
标签: c++ math overloading
versions in <cmath> 用于浮点类型,因此没有明确的最佳匹配。整数类型的重载在<cstdlib> 中,因此其中之一将产生良好的匹配。如果您在不同的类型上使用abs,您可以同时使用包含并让重载解析来完成它的工作。
#include <cmath>
#include <cstdlib>
#include <iostream>
int main()
{
unsigned int a = 5, b = 10, c;
c = std::abs(a-b);
std::cout << c << "\n"; // Ooops! Probably not what we expected.
}
另一方面,这不会产生正确的代码,因为表达式a-b 不会调用integer promotion,所以结果是unsigned int。真正的解决方案是使用有符号整数类型进行差分,以及整数类型std::abs 重载。
【讨论】:
如您所见 here,没有 cmath 函数 abs 接受无符号整数。这是因为无符号整数永远不会是负数。请尝试执行以下操作:
int a = 5, b = 10;
int c = abs(a-b);
在这种情况下,c = 5 符合预期。
【讨论】:
你可以使用三元运算符:
c = (a > b) ? a - b : b - a;
【讨论】: