文章目录
一、简介
1.作用
组合代码时,划分逻辑区域,区分相同名字的命名使用,解决名字冲突。
我们称其为namespace,命名空间/名称空间
2.作用域限定符(:?
表示作用域或所属关系,如:
ParterA::function();
ParterB::function();
在命名空间之外就要用作用限定符,格式:<命名空间名字>::<变量或函数名>
3.名称空间合并
因为命名空间是为了区分使用相同名字的变量,所以无相同变量的命名空间就可以合并。
如:
#include<iostream>
using namespace std; //这个写上是为了使用cout函数
namespace alpha //定义命名空间
{
int x = 1;
}
namespace beta
{
int x = 2;
}
int main()
{
cout << alpha::x << endl;
cout << beta::x<<endl;
}
二、定义命名空间
1.声明和定义分开
名称空间内容可以声明和定义分开
如:
#include<iostream>
using namespace std;
namespace alpha
{
int x = 1;
void part(); //这只是声明,注意要标明返回值类型
}
void alpha::part() //定义指定命名空间里的函数
{
cout << 2<<endl;
}
int main()
{
cout << alpha::x << endl;
alpha::part(); //这才是使用
}
2.命名空间嵌套
允许嵌套使用
namespace alpha
{
namespace beta
{
int x=1;
}
}
//使用时就是alpha::beta::x
命名空间别名:解决使用命名空间嵌套要写的太长
namespace gamma=alpha::beta;
gamma::x
三、使用命名空间
1.标准命名空间std
使用cin,cout,endl,string的函数,容器等需要使用命名空间std。
std可以理解为standard
2. using编译指令
在多函数程序中使用using编译指令和不使用的:
(自定义命名空间也可以使用)
- ①using namespace std。将using放在全局变量处所有函数定义前,让所有函数使用它。
- ②using namespace std。放在特定函数中,只让需要访问命名空间std的函数访问它
- ③using std。在特定的函数里使用using std::cout;的指令,就能使用cout
- ④std。在需要使用命名空间时,
std::cout << "words" << std::endl;
(1) 写法①:using namespace std
放在函数定义前就ok:放在函数声明前后都行
/*放在函数声明前也行*/
#include<iostream>
using namespace std;
int fa(int);
void fb(int);
int main() {
cout << fa(10) << endl;
fb(10);
return 0;
}
int fa(int n) {
return 10 + n;
}
void fb(int n) {
cout << n + 10;
}
/*放在函数声明后也行*/
#include<iostream>
int fa(int);
void fb(int);
using namespace std;
int main() {
cout << fa(10) << endl;
fb(10);
return 0;
}
int fa(int n) {
return 10 + n;
}
void fb(int n) {
cout << n + 10;
}
(2)写法②:using namespace std
#include<iostream>
int fa(int);
void fb(int);
int main() {
using namespace std;
cout << fa(10) << endl;
fb(10);
return 0;
}
int fa(int n) {
return 10 + n;
}
void fb(int n) {
//main()函数里的作用不到这里,main()和fb()的using namespace std;各管各的
using namespace std;
cout << n + 10;
}
(3)写法③using std
#include<iostream>
int fa(int);
void fb(int);
int main() {
using std::cout;
using std::endl;
cout << fa(10) << endl;
fb(10);
return 0;
}
int fa(int n) {
return 10 + n;
}
void fb(int n) {
using std::cout;
cout << n + 10;
}
(4)写法④std
#include<iostream>
int fa(int);
void fb(int);
int main() {
std:: cout << fa(10) << std::endl;
fb(10);
return 0;
}
int fa(int n) {
return 10 + n;
}
void fb(int n) {
std::cout << n + 10;
}
(5)使用不同的using namespace xxx冲突
注意:使用using namespace std命名空间,再使用含有冲突命名的命名空间,冲突命名还是冲突
如:
#include<iostream>
using namespace std;
namespace alpha
{
int x = 1;
}
namespace beta
{
int x = 2;
}
int main()
{
using namespace alpha;
cout << x << endl; //正常
using namespace beta;
cout << x << endl; //冲突
return 0;
}