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