c++ - 为什么在使用 "using namespace std;"和 "bits/stdc++.h"时会在此代码中出现错误?

标签 c++ function namespaces ambiguous name-lookup

实际上,这段代码在“DEV C++”中运行良好,但是当我把它放到我的“Hacker-Rank”面板中时,它给出了这个错误“对函数的引用不明确”,尽管所有在线编译器都给出了错误......

我不认为这里的函数重载是中断的地方,因为这个错误主要来自函数重载。

#include <bits/stdc++.h>
#include <cstdio>
#include<iostream>

using namespace std;


int function(int n);

int main()
{
    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');    

    if(n<=0){
        return(0);
    }
    else{
        function(n);
    }

}
int function(int n)
{
    if (n<=9)
    {
        cout<<"experiment";
    }
    
    else{
        cout<<"Greater than 9";
    }
    return 0;
}

The error with clang is :

<source>:20:9: error: reference to 'function' is ambiguous
        function(n);
        ^
<source>:8:5: note: candidate found by name lookup is 'function'
int function(int n);
    ^
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/11.0.0/../../../../include/c++/11.0.0/bits/std_function.h:111:11: note: candidate found by name lookup is 'std::function'
    class function;
          ^
// ... and more ....

最佳答案

对于初学者来说,这个 else 代码块

else{
    function(n);
}

什么都不返回。

虽然这是允许的,但会使程序的读者感到困惑,因为他们希望如果 if 子语句中有明确的 return 语句,那么 else 子语句中应该有类似的 return 语句。

由于 using 指令,全局 namespace 中声明的名称 function 似乎与标准名称 std::function 冲突。

using namespace std;

else{
    return ::function(n);
}

关于c++ - 为什么在使用 "using namespace std;"和 "bits/stdc++.h"时会在此代码中出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65122780/

相关文章:

c++ - tcp/ip ssh隧道传输数据时如何避免重复读取数据?

c++ - 当服务器重新启动并且客户端收到 WSAECONNRESET 错误代码时,我是否应该重新创建整个套接字

c++ - 有什么简单的方法可以找到当前的工作目录吗? C++

c++ - 将函数的整数返回值与 C++ 中的 bool 进行比较

python - 在我得到特定范围内的整数之前,如何继续要求用户输入?

php - 多个命名空间中的 Doctrine2 实体

php - Laravel/流明 PSR-4 : If I put classes into subdirectories do I have to use different namespaces then?

c++ - 使用相同的构造函数参数初始化所有元素或 std::array

c++ - 将显式实例化的函数模板与转换相匹配

动态的 php 命名空间