C++ 全局变量“计数”不明确
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11271889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global variable "count" ambiguous
提问by Nawaz
#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];
}
I used this function with gcc 4.3.4, and got the following error:
我在 gcc 4.3.4 中使用了这个函数,并得到以下错误:
prog.cpp: In function ‘int f(int)':
prog.cpp:38: error: reference to ‘count' is ambiguous
On my local machine (mingw32), the error I got was this one, although it's not for int 'cache[]'
.
在我的本地机器(mingw32)上,我得到的错误是这个,尽管它不是针对int 'cache[]'
.
Any reason why?
有什么理由吗?
回答by Nawaz
The problem is all because of the second line here:
问题都是因为这里的第二行:
#include <algorithm>
using namespace std;
The line using namespace std
brings all the names from <algorithm>
which also has a function called count
, and in your code, you've declared a variable count
. Hence the ambiguous error.
该行using namespace std
带来了所有名称,<algorithm>
其中还有一个名为 的函数count
,并且在您的代码中,您已经声明了一个变量count
。因此出现了模棱两可的错误。
The solution is to neverwrite using namespace std
. It is bad bad bad.
解决方案是永远不要写using namespace std
. 这是坏坏坏。
Instead, use std::cout
, std::cin
, std::endl
, std::count
and so on, in your code.
相反,使用std::cout
,std::cin
,std::endl
,std::count
等等,在你的代码。