cmath重载函数C ++的问题 [英] problems with cmath overloaded functions C++

查看:187
本文介绍了cmath重载函数C ++的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用cmath的abs()函数,但Visual Studio说它是重载的,我甚至不能使用像这样:

I need to use cmath's abs() function, but Visual Studio says it's overloaded and I can't even use something like this:

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

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

I don't know how to use it properly.

推荐答案

< cmath> 中的 =nofollow>版本适用于浮点类型,因此没有明确的最佳匹配。整数类型的重载在 < cstdlib> ,因此其中一个会产生良好的匹配。如果您在不同类型上使用 abs ,您可以同时使用includes和让重载解析完成它的工作。

The versions in <cmath> are for floating point types, so there is no unambiguously best match. The overload for integral types are in <cstdlib>, so one of those will yield a good match. If you are using abs on different types, you can use both includes and let overload resolution do its work.

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

另一方面,这不会产生正确的代码, ab 不会调用整数提升,因此结果是 unsigned int 。真正的解决方案是使用有符号整数类型的差异,以及整数类型 std :: abs 重载。

On the other hand, this doesn't yield correct code, since the expression a-b does not invoke integer promotion, so the result is an unsigned int. The real solution is to use signed integral types for differences, as well as the integral type std::abs overloads.

这篇关于cmath重载函数C ++的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆