C++命名空间

来源:互联网 发布:移动网络初始密码 编辑:程序博客网 时间:2024/06/05 03:47

C++命名空间实际上就是一个由程序设计者命名的内存区域,程序设计者可以根据需要指定一些有名字的空间域,把一些全局实体分别放在各个命名空间中,从而与其他全局实体分隔开来。

例如: namespace name   //指定命名空间为name

接下来我们直接上代码:

1、

#include <iostream>int a = 30 ; //声明一个HotDog名字空间namespace HotDog{int a = 20 ; namespace  HotPig{int a = 10 ; };void say_hello(void);};//实现say_hello()方法void HotDog::say_hello(void){printf("hello hotdog\n");}int main(void){/*使用::新运算符,用于解决名字冲突*/printf("a:%d \n" , HotDog::HotPig::a);printf("a:%d \n" , HotDog::a);printf("a:%d \n" , ::a);HotDog::say_hello();return 0 ;}</span>

2、

#include <iostream>int a = 30 ; namespace HotDog{typedef unsigned int U32 ; int a = 20 ; namespace  HotPig{int a = 10 ; };U32 say_hello(U32 a);};HotDog::U32 HotDog::say_hello(HotDog::U32 a){printf("hello hotdog a:%d \n" , a);}int main(void){printf("a:%d \n" , HotDog::HotPig::a);printf("a:%d \n" , HotDog::a);printf("a:%d \n" , ::a);//HotDog::say_hello();HotDog::U32 a = 100 ; HotDog::say_hello(a);return 0 ;}</span>
3、

#include <iostream>int c = 30 ; namespace  myspace{int a ; int b ; int c = 20 ; void say_hello(void){printf("hello world \n");}};using namespace myspace ; int main(void){//这里的::相当于C语言结构体访问的.和->printf("c : %d \n" ,myspace::c);printf("c : %d \n" , ::c);//·ÃÎÊsay_hello·½·¨ myspace::say_hello();return 0 ;}






0 0
原创粉丝点击