一个中大型软件每每由多名程序员共同开发,会使用大量的变量和函数,当有两我的都同时定义了一个名字相同的全局变量或函数的时候,如果把他们的代码整合在一块编译,此时编译器就会提示变量或函数重复定义,C++为了解决这个问题,便引用了命名空间(namespace)的概念。ios
namespace 是C++中的关键字,用来定义一个命名空间,语法格式为:程序员
namespace name{ //variables, functions, classes }
name
是命名空间的名字,它里面能够包含变量、函数、类、typedef、#define 等,最后由{ }
包围。函数
注意:也能够不用写name,若定义了一个没有名字的命名空间,则其内部的代码只能在这个文件里面用。spa
namespace { int myAge = 0; }
若要使用命名空间中定义的变量或函数,须要指名它们所在的命名空间,如:code
#include <stdio.h> #include <iostream> using namespace std; namespace DJ{ int myAge = 0; } int main() { DJ::myAge = 5; cout << "my age is: "<< DJ::myAge << endl; return 0; }
::
是一个新符号,称为域解析操做符,在C++中用来指明要使用的命名空间。blog
还能够这样写(直接使用using声明):开发
#include <stdio.h> #include <iostream> using namespace std; namespace DJ{ int myAge = 0; } int main() { using DJ::myAge; myAge = 5; cout << "my age is: "<< myAge << endl; return 0; }
在代码的开头使用using声明DJ:myAge,这样若是接下来的代码中出现了未指明命名空间的myAge,就使用DJ:myAge,不过要使用别的命名空间中定义的myAge,则仍然须要显示声明。编译器
还能够写成这样:io
#include <stdio.h> #include <iostream> using namespace std; namespace DJ{ int myAge = 0; } int main() { using namespace DJ; myAge = 5; cout << "my age is: "<< myAge << endl; return 0; }
若是命名空间 DJ中定义的其余的变量,样具备 myAge变量的效果。编译
命名空间内部不只能够声明或定义变量,对于其它能在命名空间之外声明或定义的名称,一样也都能在命名空间内部进行声明或定义,例如类、函数、typedef、#define 等均可以出如今命名空间中。
新建一个纯C++项目(QT)时,QT默认新建的main.cpp文件以下:
#include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; return 0; }
实际上是省略了cout的命名空间,也能够写成这样:
#include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; }