文章目录
1.什么是匿名命名空间?
匿名命名空间就是一个没有名字
的命名空间。
namespace
{
func()
{
...
}
}
2.匿名命名空间有什么用处?
- 匿名命名空间里的内容只能被本文件调用,不能被外部引用;
- 匿名命名空间中的变量特点跟全局变量一样,而函数特点像是添加了static的功能一样。两者仅此在本文件使用
3.实验
3.1在匿名空间中引用其它命名空间
#include <iostream>
using namespace std;
namespace np
{
void func1()
{
cout << "this is func1" << endl;
}
}
namespace
{
void func2()
{
np::func1();
}
}
int main()
{
func2();
return 0;
}
实验结果
3.2匿名命名空间中引用自己命名空间中的方法
#include <iostream>
using namespace std;
namespace
{
int cnt = 0;
void func2()
{
cout << "this is func2" << endl;
}
}
int main()
{
cnt += 1; //像全局变量一样读取
cout << cnt << endl;
func2(); //像全局变量一样读取
return 0;
}
实验结果
3.3其他命名空间中引用匿名命名空间中的方法
#include <iostream>
using namespace std;
namespace
{
void func2()
{
cout << "this is func2" << endl;
}
}
namespace np
{
void func1()
{
func2();
}
}
int main()
{
np::func1();
return 0;
}
实验结果
3.4不同文件调用匿名命名空间
//test2.cpp
//namespace xxx {extern func1()}; //连名字符号都没有,无法声明....
void func1()
{
func2();
}
test1.cpp
#include <iostream>
void func1();
using namespace std;
namespace
{
void func2()
{
cout << "this is func2" << endl;
}
}
int main()
{
func1();
return 0;
}
实验结果
首先,匿名命名空间没有名字,或者说把名字给隐藏了,无法像xxx::func2()
这样子调用,并且在test2.cpp中也无法声明匿名命名空间空间(不符合语法)。
4.最后
匿名命名空间的本质是什么?
就是将命名空间的名字符号给去掉,让其他文件找不到。
C++ 新的标准中提倡使用匿名命名空间,而不推荐使用static,因为static用在不同的地方,涵义不同,容易造成混淆.另外,static不能修饰class。