27
#include <algorithm>
using namespace std;

int count = 0, cache[50];

int f(int n)
{  
    if(n == 2) count++;
    if(n == 0 || n==1) return n;
    else if (cache[n] !=- 1) return cache[n];
    else cache[n]= f(n-1) + f(n-2);
    return cache[n]; 
}

我在 gcc 4.3.4 中使用了这个函数,得到了以下错误:

prog.cpp: In function ‘int f(int)’:
prog.cpp:38: error: reference to ‘count’ is ambiguous

在我的本地机器(mingw32)上,我得到的错误是这个,虽然它不是针对int 'cache[]'.

有什么理由吗?

4

4 回答 4

82

问题都是因为这里的第二行:

#include <algorithm>
using namespace std;

该行using namespace std带来了所有名称,<algorithm>其中还有一个名为 的函数count,并且在您的代码中,您已经声明了一个变量count。因此,模棱两可的错误。

解决方案是永远不要using namespace std. 很糟糕很糟糕。

相反,请在您的代码中使用std::coutstd::cinstd::endl等。std::count

于 2012-06-30T06:20:55.770 回答
1

I think I may have figured this out. I have found that removing the using namespace std doesn't help, but when I change the name of the variable to something which is less common, like count can be changed to cnt or some personal versions like knt or isCycle. I don't exactly know what is the reason behind this.

于 2020-10-29T05:56:38.817 回答
0

yeah idk but changing the name to less common variable name works fine in case of mine

于 2020-11-12T18:06:38.173 回答
0

simply change the variable name as it 'count' matches the internal keyword while we declare using namespace std.

于 2021-11-06T09:02:50.427 回答