Declaration region (declaration region) A declaration region is a region in which declarations can be made. For example, global variables can be declared outside the function. For such variables, the declaration area is the file where they are declared. For a variable declared in a function, its declaration area is the code block where it is declared.
Potential scope (potential scope) The potential scope of a variable starts at the point of declaration and ends at the end of its declaration area. Therefore, the potential scope is smaller than the declaration area, because the variable must be defined before it can be used. + Namespace features
/* Ok 1. 名称空间可以是全局的 */namespace Jack {
double pail;voidfetch();int pal;}/* Ok */namespace Jill {
doublebucket(double n){
...}double fetch;int pail;}/* 2. 名称空间是开放的(open),可以把名称加入到已有的名称空间中 */namespace Jack {
int b;}/* 3. 名称空间可以在另一个名称空间中 */namespace A {
namespace B {
int a;int b;}}intmain(){
/* 4. 名称空间不可以位于代码块中,默认情况下,
在名称空间中声明的名称的链接性为外部的(除非它引用了常量) */// namespace hello {} No/* use namespace */// 通过作用域解析运算符::,使用名称空间来限定该名称
Jack::Pail =12.34;/* 未被修饰的名称(如pail)称为未限定的名称(unqualified name); 包含名称空间的名称(如Jack::pail)限定的名称 */}
Using declaration and using compiler directive C++ provides using declaration and using compiler directive to simplify the use of names in the namespace. The using declaration makes specific identifiers available, and the using compilation makes the entire namespace available.
/* using 声明 */using Jack::pail;// a using declaration/* using编译指令与using声明比较 */intmain(){
/* using声明 */double pail;using Jack::pail;// not allow,当某个名称已经在函数中存在,不可以使用using声明导入相同的名称/* 2. using编译指令 *//* 使用using编译指令导入一个名称空间与使用using声明是不同的,更像是使用大量的作用域解析运算符,*/usingnamespace Jack;// ok 但是相同的局部名称将隐藏名称空间名,就像隐藏同名的全局变量一样
pail =3;
cout << Jack::pail << endl;// 0return0;}
Use variables declared in the named namespace instead of using external global variables
Use variables declared in unnamed namespaces instead of static global variables
If you develop a function library or class library, put it in a namespace. C++ advocates putting the standard function library in the namespace std to expand functions from the C language. But not all compilers have completed this excessive
Only use the compiler directive using as a stopgap measure to convert old code to use namespace
Do not use the using compiler directive in the header file. First of all, this obscures the need to make those names available; in addition, the order in which the header files are included may affect the behavior of the program. If you must use the using compiler directive using, it should be placed after #include
When importing names, the preferred method of using scope resolution operators or using declarations
For the using statement, it is preferred to set its scope to be local rather than global.