本段测试代码包括如下内容:
(1) 如何访问namespace中声明的名称;
(2) namespace导致的相关冲突;
(3) namespace可嵌套;
(4) 可以在namespace中使用using声明和using编译命令;
(5) 未命名的namespace:其作用域为定义该namespace所在的声明区域。C++推荐用来替代static定义静态变量。
1 #include <iostream> 2 3 using namespace std; 4 5 namespace jerry{ 6 int height; 7 int weight; 8 void showHeight(); 9 string name; 10 } 11 12 // 13 namespace jerry{ 14 void showHeight() 15 { 16 cout<<"Method 3: Jerry height: "<<height<<" kg"<<endl; 17 } 18 } 19 20 namespace elements 21 { 22 namespace fire 23 { 24 int flame; 25 using namespace jerry; //(4) can use 'using' in namespace define 26 using std::cout; 27 } 28 float water; 29 } 30 31 //(5) no name namespace 32 //其作用域为定义时所在的声明域,可用来替换static变量,这是C++标准推荐的行为 33 namespace { 34 string data; 35 } 36 37 void testFun(); 38 int main() 39 { 40 cout<<"This code is to test namespace"<<endl; 41 /*not allowed to define namespace in code segment 42 //Error 43 namespace jerry{ 44 int height; 45 int weight; 46 } 47 */ 48 49 //(1) To access the data in namespace 50 //Method 1: 作用域解析符 51 jerry::height = 165; 52 cout<<"Method 1: Jerry height: " << jerry::height <<" cm"<<endl; 53 54 //Method 2: using声明 55 using jerry::weight; 56 weight = 64; 57 cout<<"Method 2: Jerry weight: " << weight<<" kg"<<endl; 58 59 //Method 3: using编译指令:All the define data in namespace jerry can be access. 60 using namespace jerry; 61 showHeight(); 62 63 //(2) about name conflict 64 { 65 jerry::name = "Jerry"; 66 string name = "Tom"; 67 //using jerry::name; Error 68 cout << "name: "<<name<<endl; 69 /* 70 This method will lead conflict with locall parameter 71 using jerry::name; 72 cout << "name: "<<name<<endl; 73 */ 74 75 cout << "name: "<<jerry::name<<endl; 76 using namespace jerry; 77 //局部变量会覆盖jerry命名空间的name定义 78 cout << "name: "<<name<<endl; 79 80 } 81 82 //(3) namespace can nest 83 elements::fire::flame = 2; 84 using namespace elements::fire; 85 86 //(5) no name namespace 87 //其作用域为定义时所在的声明域,可用来替换static变量,这是C++标准推荐的行为 88 data = "hello"; 89 cout<<"No name namespace: data: " << data <<endl; 90 testFun(); 91 92 } 93 94 void testFun() 95 { 96 97 /*not allowed to define namespace in code segment 98 //Error 99 namespace jerry{ 100 int height; 101 int weight; 102 } 103 */ 104 105 //(5) no name namespace 106 data = "hello in function"; 107 cout<<"No name namespace: data: " << data <<endl; 108 }
运行结果为: