c – 全局变量“count”含糊

前端之家收集整理的这篇文章主要介绍了c – 全局变量“count”含糊前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. #include <algorithm>
  2. using namespace std;
  3.  
  4. int count = 0,cache[50];
  5.  
  6. int f(int n)
  7. {
  8. if(n == 2) count++;
  9. if(n == 0 || n==1) return n;
  10. else if (cache[n] !=- 1) return cache[n];
  11. else cache[n]= f(n-1) + f(n-2);
  12. return cache[n];
  13. }

我用gcc 4.3.4这个函数,并得到以下错误

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

在我的本地机器上(mingw32),我得到的错误this one,虽然不是int’cache []’.

有什么原因吗

解决方法

问题是因为这里的第二行:
  1. #include <algorithm>
  2. using namespace std;

使用namespace std的行将所有名称从< algorithm>它也有一个叫做count的函数,在你的代码中你已经声明了一个变量的计数.所以这个模糊的错误.

解决方案是永远不要使用命名空间std写.这是坏坏的坏

相反,在你的代码中使用std :: cout,std :: cin,std :: endl,std :: count等等.

猜你在找的C&C++相关文章