【问题标题】:When using abs() it shows "abs is ambiguous" but when I try it on another editor it works使用 abs() 时,它显示“abs is ambiguous”,但是当我在另一个编辑器上尝试它时它可以工作
【发布时间】:2020-09-09 04:50:14
【问题描述】:

在我的代码中 abs() 不起作用,但是当放入不同的代码编辑器时它确实起作用。我不知道该怎么办。到处都找不到答案。请帮忙。错误:(“abs”不明确C/C++(266))

#include <iostream>
#include <cstdlib>

using namespace std;

int main(){

    int x = -1;
    int a = abs(x);

    cout<< a;

}

【问题讨论】:

标签: c++ visual-studio-code


【解决方案1】:

更多信息会有所帮助。此处无需添加“使用命名空间标准”。您可以尝试修改“int a = abs(x);” ==> "int a = ::abs(x);"

【讨论】:

  • #include &lt;cstdlib&gt;,正如问题中所写,需要将所有名称放入std,并且允许将名称放入全局命名空间。所以::abs 不需要工作。 std::abs 将看到所有名称。要使用::abs,适当的标头是#include &lt;stdlib.h&gt;,它将所有名称放入全局命名空间并允许将名称放入std
  • 我在 Visual Studio 2019(C++17) 上进行了上述测试,效果很好。实际上,cstdlib 已经包含了 stdlib.h
  • 是的,这就是重点:它可能起作用;它不是必需工作。甚至在它现在可以工作的编译器的未来版本中也不行。
【解决方案2】:
#include <iostream>
#include <cstdlib>

using namespace std;

int main(){

    int x = -1;
    int a = fabs(x);

    cout<< a;

}


#include <iostream>
#include <stdlib.h>


int main() {

    int x = -1;
    int a = abs(x);

    std::cout << a;

}

【讨论】:

  • 为了完整和减少意外,示例应包括
猜你喜欢
  • 2021-11-29
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多