全局变量“count”不明确

新手上路,请多包涵
#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[]'

有什么理由吗?

原文由 user801154 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

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

 #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 .因此,模棱两可的错误。

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

相反,请在您的代码中使用 std::coutstd::cinstd::endlstd::count 和so onbaf

原文由 Nawaz 发布,翻译遵循 CC BY-SA 3.0 许可协议

当我们使用命名空间 std 声明时,只需更改变量名称,因为它的“计数”与 internal 关键字匹配。

原文由 SHIVAM KUMAR 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题