简体   繁体   English

cmath重载函数C ++的问题

[英]problems with cmath overloaded functions C++

I need to use cmath's abs() function, but Visual Studio says it's overloaded and I can't even use something like this: 我需要使用cmath的abs()函数,但Visual Studio说它已经重载了,我甚至无法使用这样的东西:

unsigned a = 5, b = 10, c;
c = abs(a-b);

I don't know how to use it properly. 我不知道如何正确使用它。

The versions in <cmath> are for floating point types, so there is no unambiguously best match. <cmath>中的版本适用于浮点类型,因此没有明确的最佳匹配。 The overload for integral types are in <cstdlib> , so one of those will yield a good match. 整数类型的重载在<cstdlib> ,因此其中之一将产生良好的匹配。 If you are using abs on different types, you can use both includes and let overload resolution do its work. 如果您在不同类型上使用abs ,则可以同时使用include和让过载解析发挥作用。

#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.
}

On the other hand, this doesn't yield correct code, since the expression ab does not invoke integer promotion , so the result is an unsigned int . 另一方面,这不会产生正确的代码,因为表达式ab不会调用整数提升 ,因此结果是unsigned int The real solution is to use signed integral types for differences, as well as the integral type std::abs overloads. 真正的解决方案是对差异使用带符号的整数类型,以及对std::abs整数类型进行重载。

As you can see here , there is no cmath function abs that takes an unsigned integer. 如您在此处看到的,没有cmath函数abs接受无符号整数。 This is because unsigned integers are never negative. 这是因为无符号整数从不为负。 Try doing the following instead: 请尝试执行以下操作:

int a = 5, b = 10;
int c = abs(a-b);

In this case, c = 5 as expected. 在这种情况下, c = 5如预期。

您可以使用三元运算符:

c = (a > b) ? a - b : b - a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM