码迷,mamicode.com
首页 > 其他好文 > 详细

命名空间

时间:2016-07-05 06:24:19      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

 

//自定义一个命名空间,可以解决变量重名的问题

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 namespace myspace//自定义一个命名空间,可以解决变量重名的问题
 5 {
 6     int a(15);
 7 }
 8 
 9 void main()
10 {
11     int a(5);
12 
13     std::cout << "a=" << a << std::endl;//main函数a
14 
15     std::cout << "a=" << myspace::a << std::endl;//命名空间的a
16 
17     system("pause");
18 }

 

//自定义一个命名空间,可以解决函数重名的问题

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 namespace myspace//自定义一个命名空间,可以解决变量重名的问题
 5 {
 6     void print()
 7     {
 8         std::cout << "hello" << std::endl;
 9     }
10 }
11 
12 void print()
13 {
14     std::cout << "world" << std::endl;
15 }
16 
17 void main()
18 {
19     print();
20 
21     myspace::print();
22 
23     system("pause");
24 }

 

//匿名命名空间,变量、函数可以直接调用

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 namespace//匿名命名空间,变量、函数可以直接调用
 5 {
 6     int a(3);
 7     
 8     void print()
 9     {
10         std::cout << "hello" << std::endl;
11     }
12 }
13 
14 void main()
15 {
16     std::cout << a << std::endl;
17 
18     print();
19 
20     system("pause");
21 }

 

//命名空间别名

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 namespace run
 5 {
 6     int a(3);
 7 
 8     char *str("hello");
 9 }
10 namespace r = run;//命名空间别名
11 
12 void main()
13 {
14     std::cout << r::a << std::endl;
15 
16     std::cout << r::str << std::endl;
17 
18     system("pause");
19 }

 

//使用了using namespace以后,调用命名空间成员可以不用写命名空间名称了

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 namespace run
 5 {
 6     int a(3);
 7 
 8     char *str("hello");
 9 }
10 using namespace run;
11 
12 void main()
13 {
14     std::cout << a << std::endl;//使用了using namespace以后,调用命名空间成员可以不用写命名空间名称了
15 
16     system("pause");
17 }

 

命名空间

标签:

原文地址:http://www.cnblogs.com/denggelin/p/5642202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!