Warm tip: This article is reproduced from serverfault.com, please click

c++-为什么在使用“ using namespace std;”时在此代码中出现错误?

(c++ - Why do I get an error in this code when using "using namespace std;" and "bits/stdc++.h"?)

发布于 2020-12-03 09:03:47

实际上,此代码在“ 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;
}

lang的错误是

<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 ....
Questioner
fly_high
Viewed
0
Vlad from Moscow 2020-12-03 17:15:53

对于初学者来说,这是其他代码块

else{
    function(n);
}

什么也不返回。

尽管它被允许,但是使程序的读者感到困惑,因为他们希望,如果if子语句中有一个显式的return语句,那么else子语句中应该有一个类似的return语句。

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

using namespace std;

else{
    return ::function(n);
}