【问题标题】:problems with cmath overloaded functions C++cmath 重载函数 C++ 的问题
【发布时间】:2013-03-05 07:17:04
【问题描述】:

我需要使用 cmath 的 abs() 函数,但 Visual Studio 说它超载了,我什至不能使用这样的东西:

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

我不知道如何正确使用它。

【问题讨论】:

标签: c++ math overloading


【解决方案1】:

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 重载。

【讨论】:

    【解决方案2】:

    如您所见 here,没有 cmath 函数 abs 接受无符号整数。这是因为无符号整数永远不会是负数。请尝试执行以下操作:

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

    在这种情况下,c = 5 符合预期。

    【讨论】:

      【解决方案3】:

      你可以使用三元运算符:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-13
        • 2012-06-12
        • 1970-01-01
        • 2012-12-22
        相关资源
        最近更新 更多