写了个汉诺塔,使用全局变量count来记录步数,结果Error:count不明确
#include <iostream> using namespace std; int count = 0; void hanoi(int num, char source, char through, char target){ if (num == 0) return; hanoi(num - 1, source, target, through); printf("%d from %c to %c ", num, source, target); count++; hanoi(num - 1, through, source, target); }
后来才知道 std命名空间里有std::count,所以与全局变量count冲突
std::count
template <class InputIterator, class T> typename iterator_traits<InputIterator>::difference_type count(InputIterator first, InputIterator last, const T& val);
所以修改方法有以下几种:
1.全局变量count改为cnt(或其他名称)
2.使用count的地方改为::count
#include <iostream> using namespace std; int count = 0; void hanoi(int num, char source, char through, char target){ if (num == 0) return; hanoi(num - 1, source, target, through); printf("%d from %c to %c ", num, source, target); ::count++; hanoi(num - 1, through, source, target); }
3.不要使用using namespace std,使用using namespace std是不好的习惯