c++命名空间 namespace学习

咱们为何须要命名空间?

咱们假设一下这种状况,在A班中,有一名同窗叫小明,在B班中,也有一名同窗叫小明,如今两个班的同窗一块儿聚会,老师找A班的小明,这时候他在人群中喊一声小明确定两个小明都过来了,这个时候B班小明就白跑一趟了,为了不这种尴尬,老师只要喊“A班的小明过来一下就好了”。在c++已经其余某些语言中,也是这个道理,在不少大型项目中,因为可能多人一块儿开发,不免出现相同名字的变量,这个时候咱们就须要namespace了,在调用同名变量时,另外加上它的namespace,这样就避免了出错。ios

1.命名空间实例

//namespace study
#include<iostream>
using namespace std;
namespace first_space{
	void func(){
		cout<<"my first_space"<<endl;
	}
}
namespace second_space{
	void func(){
		cout<<"my second_space"<<endl;
	}
}
int main(){
	first_space::func();
	second_space::func();
}

2.using指令

您可使用 using namespace 指令,这样在使用命名空间时就能够不用在前面加上命名空间的名称。这个指令会告诉编译器,后续的代码将使用指定的命名空间中的名称。c++

//namespace study
#include<iostream>
using namespace std;
namespace using_space{
	void beusing(){
		cout<<"I am using"<<endl;
	}
}
using namespace using_space;

//namespace using_space{
//	void beusing(){
//		cout<<"I am using"<<endl;
//	}
//}
int main(){
	beusing();

}

这里注意using namespace必须在被调用空间定义后再使用。spa

using 指令也能够用来指定命名空间中的特定项目。例如,若是您只打算使用 std 命名空间中的 cout 部分,您可使用以下的语句:code

#include <iostream>
using std::cout;
 
int main ()
{
 
   cout << "std::endl is used with std!" << std::endl;
   
   return 0;
}

3.不连续的命名空间

命名空间能够定义在几个不一样的部分中,所以命名空间是由几个单独定义的部分组成的。一个命名空间的各个组成部分能够分散在多个文件中。开发

因此,若是命名空间中的某个组成部分须要请求定义在另外一个文件中的名称,则仍然须要声明该名称。下面的命名空间定义能够是定义一个新的命名空间,也能够是为已有的命名空间增长新的元素:编译器

namespace namespace_name {
   // 代码声明
}

4.嵌套的命名空间

在c++中,命名空间的使用是能够嵌套的。以下所示:it

namespace namespace_name1 {
   // 代码声明
   namespace namespace_name2 {
      // 代码声明
   }
}

注意,引用父级命名空间并不能直接调用子空间里的变量,以下:io

#include<iostream>
using namespace std;
namespace first_space{
	namespace second_space{
		int a=0,b=1;
	}
}
using namespace first_space;
int main(){
	cout<<a<<" "<<b<<endl; //错误代码,a未定义
	return 0;
}

正确调用方式以下:编译

#include<iostream>
using namespace std;
namespace first_space{
	namespace second_space{
		int a=0,b=1;
	}
}
using namespace first_space::second_space;
int main(){
	cout<<a<<" "<<b<<endl;
	return 0;
}