C++入门篇一


双冒号(::)的作用:作用域运算符,全局作用域

 

void   LOL::game1(){//在LOL命名空间下面的game1
    cout << "LOL游戏开始" << endl;

}

 

namespace命名空间:
用途解决名称冲突问题
必须在全局作用域下声明
命名空间可以放入函数,变量,结构体,类
命名空间可以嵌套命名空间
命名空间是开放的,可以随时加入新的成员
匿名命名空间

 1.嵌套命名空间

namespace  A {
	int  m_a = 10;
	namespace  B {
		int  m_b = 100;
	}
}
cout << "嵌套命名空间" << A::B::m_b << endl;//运行A房间里面B房间里面的m_b

 

 

2.匿名命名空间:

如果写了没有命名的命名空间,相当于是写了static  int  m_a,static  int  m_d,只能是在当前文件内使用

//如果写了没有命名的命名空间,相当于是写了static  int  m_a,static  int  m_d,只能是在当前文件内使用
namespace {
    int  num1 = 100;
}
cout << "匿名空间下的" << num1 << endl;//直接是可以调用匿名空间下的num1,不用加::

3.命名空间可以起别名:

namespace  new1 {//命名空间new1,
    int  new_num = 100;

}
namespace  old = new1;//给这个命名空间起别名,重新复制new1命名空间
cout << "别名下的num" << old::new_num << endl;

 

 

using声明和using编译指令:

using  namespace  std;打开std的命名空间

1.打开多个房间,要指出是哪一个房间才可以

namespace  tets02{//声明两个房间
    int  num01 = 123;
}
namespace  test04 {
    int  num01 = 434;
}

打开这个两个房间

void  test3() {
    using  namespace tets02;//打开这个test02这个房间,仅仅只是打开了这个房间,还是就就近原则
    using  namespace  test04;//打开test04这个房间,如果不声明的话,无法确定num01是那个房间的
    cout << "test3  num01    " << test04::num01 << endl;//在这里必须要声明是哪一个房间的num01才可以,否则无法找到
}

结果:

2.二义性,就近原则

虽然打开了房间,但是如果房间比较远的话,还是去较近的为准

namespace  tets02{
    int  num01 = 123;
}
//void  test3() {
    //int  num01 = 198;
    //using  namespace tets02;//打开这个test02这个房间,仅仅只是打开了这个房间,还是就就近原则
    //cout << "test3  num01" << num01 << endl;
//}

结果:取的是自己的num01,虽然打开了test01房间

 

下面报错了,打开房间test02并且使用这个num01

namespace  tets02{
    int  num01 = 123;
}
void  tets01() {
    int  num01 = 1;
    //using声明,注意避免二义性问题
    //写了using声明之后,下面这行代码说明所看到的的num01是使用了test02命名空间下面的
    //但是编译器又有就近原则
    //二义性
    using   tets02::num01;//打开房间并且使用num01,这里已经是两次声明test02房间下面的num01了
    cout << "tets01 num01=" << num01 << endl;
}

 

猜你喜欢

转载自www.cnblogs.com/yunxintryyoubest/p/10674523.html