为什么在使用“using namespace std;”时此代码中出现错误和“位/stdc++.h”?

2024-02-26

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

clang 的错误是 https://godbolt.org/z/W69n7x:

<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 语句。

貌似这个名字function在全局名称空间中声明的名称与标准名称冲突std::function由于使用指令。

using namespace std;

Write

else{
    return ::function(n);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么在使用“using namespace std;”时此代码中出现错误和“位/stdc++.h”? 的相关文章

随机推荐