//============================================================================
// Name : prac0616NameSpace.cpp
// Author : perfey
// Version :
// Copyright : Your copyright notice
// Description : namespace
//============================================================================
#include <iostream>
using namespace std;
namespace ns1
{
int var = 1;
namespace ns2
{
int var = 2;
}
}
int var = 4;
int main() {
cout << "!!!Hello World!!!" << std::endl; // prints !!!Hello World!!!
int var = 3; // global variable
if (var > 2)
{
int var =55;
std::cout << " This is inner var = " << var <<endl;
std::cout << " This is global var = " << ::var <<endl;
std::cout << " This is namespace1 var = " << ns1::var <<endl;
std::cout << " This is namespace2 var = " << ns1::ns2::var <<endl;
}
return 0;
}
result
!!!Hello World!!!
This is inner var = 55 // 局部变量(最近的作用域,没有索引到main中第一个var = 3)
This is global var = 4 // 全局作用域(main函数外定义的全局变量)
This is namespace1 var = 1 // namespace1 应用到的
This is namespace2 var = 2 // namespace2引用到的(因为ns2嵌套在ns1里面,必须先索引ns1::ns2再索引ns2,防止外部有独立ns2的空间;; 类比文件夹,要到内层子文件夹取文件,必须逐层打开外在文件夹)