今天碰到个很小的问题,关于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只需要看作一个类即可,这个类里面有我们需要使用的变量,使用的时候去调用就可以了