为什么在使用"using namespace std;"时在此代码中出现错误?和"bits/stdc ++.h"? [英] Why do I get an error in this code when using "using namespace std;" and "bits/stdc++.h"?

查看:83
本文介绍了为什么在使用"using namespace std;"时在此代码中出现错误?和"bits/stdc ++.h"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,此代码在"DEV C ++"中可以正常工作,但是当我将其放入"Hacker-Rank"时,面板上会显示此错误功能引用不明确",尽管所有在线编译器都显示错误...

Actually this code works fine in "DEV C++", but when I put it into my "Hacker-Rank" panel it gives this error "reference to function is ambiguous", although all the online compilers are giving errors...

我不认为这里的函数重载会在某个地方中断,因为此错误主要来自函数重载.

I don't think here function overloading is somewhere interrupting, because this error mostly comes in function overloading.

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

c铛错误是:

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

推荐答案

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

For starters this else code block

else{
    function(n);
}

不返回任何内容.

尽管允许这样做,但会使程序的读者感到困惑,因为他们希望,如果if子语句中有一个显式的return语句,那么在else子语句中应有一个类似的return语句.

Though it is allowed but confuses readers of the program because they expect that if there is an explicit return statement in the if sub-statement then a similar return statement should be in the else sub-statement.

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

It seems the name function declared in the global name space conflicts with the standard name std::function due to the using directive.

using namespace std;

else{
    return ::function(n);
}

这篇关于为什么在使用"using namespace std;"时在此代码中出现错误?和"bits/stdc ++.h"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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