C++ 全局變量不明確與 using namespace std 沖突


寫了個漢諾塔,使用全局變量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是不好的習慣

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM