不要随便使用 using namespace std

今天碰到个很小的问题,关于count变量报错 :count不明确,具体代码如下:

#include "stdafx.h"
#include<iostream>
using namespace std;

int count = 0;

int main()
{
	for (int i = 0; i < 10; i++)
	{
		static  int number = 0;
		for (int j = i; j < 10; j++)
		{
			number++;
			cout << number << endl;
			count++;
		}
	}

	cout << count << endl;
}

后来发现定义的全局变量count与std里面已有的名字重复,所以为了避免这个,平时多用
using std::这样写

#include "stdafx.h"
#include<iostream>
using std::cout;
using std::endl;

int count = 0;

int main()
{
	for (int i = 0; i < 10; i++)
	{
		static  int number = 0;
		for (int j = i; j < 10; j++)
		{
			number++;
			cout << number << endl;
			count++;
		}
	}
	cout << count << endl;
}

关于namespace
namespace翻译过来就是命名空间,"命名空间"四个字听起来很复杂,为什么叫命名空间呢,说白了就是为了解决我们的命名问题,在C++的前身——C语言里是没有命名空间这个概念的,所以我们可以看到很多OpenGL里的api名字都很长,比如glInit()glfwInit()函数,两个函数不能都叫init否则编译器不知道调用哪一个,有了命名空间我们就可以在不同的namespace里面定义这些内容,这些函数就可以叫相同的名字,代码如下:

namespace A {
  	const int a = 5;
}

namespace B
{
	const int a = 6;
}

int main()
{
	std::cout << A::a << std::endl;
	std::cout << B::a << std::endl;
}

实际上namespace只需要看作一个类即可,这个类里面有我们需要使用的变量,使用的时候去调用就可以了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值