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是不好的习惯

原文链接: https://www.cnblogs.com/dj0325/p/8491649.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/269713

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午8:39
下一篇 2023年2月14日 下午8:40

相关推荐