命名空间详解
1 /*命名空间详解*/
2
3 namespace runrunrunrun
4 {
5 int a(10);
6 char *str("gogogo");
7 namespace run // 命名空间的嵌套
8 {
9 int a(9);
10 }
11 }
12
13 namespace runrunrunrun // 命名空间的拓展
14 {
15 int y(5);
16 int a(15); // 重定义错误
17 }
18
19 namespace r = runrunrunrun;// 给命名空间取一个别名
20
21
22 void main()
23 {
24 std::cout << r::run::a << std::endl;// 命名空间可以嵌套
25 std::cout << r::y << std::endl;
26 }
27
28 //----------------------------------------------
29
30 /*namespace 软件开发注意事项*/
31
32 #include<iostream>
33
34 namespace runmove// 命名空间的拓展
35 {
36 int y(5);
37 int (*padd)(int,int);// 函数指针 接口
38 class MyClass
39 {
40 public: // 类默认是私有 实现封装
41 int a;
42 };
43 }
44
45 int add(int a,int b)
46 {
47 return a+b;
48 }
49
50 int addp(int a,int b)
51 {
52 std::cout << a << b;
53 return a+b;
54 }
55
56 struct MyStruct
57 {
58 int b;// 结构体默认透明的
59 private
60 int a;// 是私有的内部可以调用外部不行
61
62 };
63
64 void main()
65 {
66 // namespace 所有数据 函数 类 对象都是共有
67 //namespace 命名空间是透明的 不能私有
68 MyStruct struct1;// 结构体内部默认公有
69 }
70
71 //------------------------------------
72
73 /*using 作用域*/
74
75 namespace mydata
76 {
77 int a(6);
78 }
79
80 namespace yourdata
81 {
82 int a(8);
83 }
84
85 using namespace mydata; // 作用域为从代码开始到结束
86 using namespace yourdata;//
87 // using 如果变量重名 会出现不明确错误 此时需要加上命名空间标示符
88
89
90 using namespace mydata;// 必须放在定义命名空间的下方
91
92 void go()
93 {
94 // 命名空间如果在块语句内部 作用域在定义开始到块语句结束
95 std::cout << mydata::a << std::endl;// a是一个未声明的标识符
96 }
97
98 void main()
99 {
100 std::cout << mydata::a << std::endl;
101
102 std::cout << a << std::endl;
103 }
104
105 //-----------------------------------------------
106
107 /*C全局变量的缺点*/
108
109 int a = 1;// 全局 出现重名无法引用全局变量
110 void main()
111 {
112 int a = 3;
113 printf("%d",a);
114 }
115
116
117 // C++
118
119 int a = 1;// 全局
120 void main()
121 {
122 int a = 3;
123 std::cout << a;// 3
124 std::cout << ::a;// 1 :: 全局
125 }
长风破浪会有时,直挂云帆济沧海
posted on 2015-05-25 22:32 Dragon-wuxl 阅读(109) 评论(0) 收藏 举报
浙公网安备 33010602011771号