命名空间:c++中由用户命名的作用域,用来处理程序中的命名冲突。
命名空间一般是处在全局作用域中,当然,全局作用域中还有函数,全局变量等。
命名空间是这样定义的:
namespace N
{
int test1;
int test2;
}
这就是命名空间为N。命名空间有以下特点:
(1)可以在多个.cpp文件下同时生成namespace N;此时都会合并在同一个命名空间中。
(2)命名空间可嵌套。
如下:
namespace N
{
int test1;
<span> </span>int test2;
<span style="white-space:pre"> </span>namespace N1
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span> int test1;
int test2;
<span style="white-space:pre"> </span>}
}
那么如果你要使用其中的变量呢?
(1)使用作用域限定符
#include<iostream>
namespace N
{
int test1;
int test2;
namespace N1
{
int test1;
int test2;
}
}
int test1 = 30;
int main()
{
N::test1 = 10; //命名空间为N中的test1
N::N1::test1 = 20; //命名空间为N1中的test1
std::cout<<N::test1<<std::endl;
std::cout<<N::N1::test1<<std::endl;
std::cout<<::test1<<std::endl; //全局变量test1
system("pause");
return 0;
}
结果:
当然,还有另一种访问方式:
(2)使用using namespace + 命名空间名
#include<iostream>
namespace N
{
int test1;
int test2;
namespace N1
{
int test1;
int test2;
}
}
using namespace N;
int main()
{
test1 = 10; //命名空间为N中的test1
N1::test1 = 20; //命名空间为N1中的test1
std::cout<<test1<<std::endl;
std::cout<<N1::test1<<std::endl;
system("pause");
return 0;
}
结果:
当你想单独使用某一个变量时,还可以这样声明一下。
#include<iostream>
namespace N
{
int test1;
int test2;
namespace N1
{
int test1;
int test2;
}
}
using N::N1::test1; //直接使用test1
int main()
{
test1 = 10; //命名空间为N1中的test1
std::cout<<test1<<std::endl;
system("pause");
return 0;
}
结果:
(3)当命名空间没名字时,该怎么使用?
#include<iostream>
namespace
{
int test1;
int test2;
namespace N1
{
int test1;
int test2;
}
}
int main()
{
test1 = 10; //命名空间为N中的test1
N1::test1 = 20;
std::cout<<test1<<std::endl;
std::cout<<N1::test1<<std::endl;
system("pause");
return 0;
}
结果:
当命名空间没名字时,也可直接使用,此时相当于全局变量。但是空间中的变量只在当前文件中可见。这时我们就会想到static(存在于静态区)。
static关键字用于修改标识符的链接属性。外部链接属性变为内部链接属性。只在当前文件可使用。
当它用于代码块内部的变量声明时,static关键字用于修改变量的存储类型,自动变量(auto)变为静态变量(static)。属性和作用域不受影响。
再回归到命名空间来说,c++中我们会用到最基本的输入输出(cin,cout),而cin,cout等都在std命名空间里,所以我们c++中一般定义:
#include<iostream>
using namespace std;
如果不说明using namespace std;我们就会用到作用域限定符std::cin,std::cout,std::endl;等等。