寫了個漢諾塔,使用全局變量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\n", 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\n", num, source, target); ::count++; hanoi(num - 1, through, source, target); }
3.不要使用using namespace std,使用using namespace std是不好的習慣