10 c++ namespaces anonymous class
我正在查看一些(C++)代码,发现类似这样的东西:
//Foo.cpp
namespace
{
void SomeHelperFunctionA() {}
void SomeHelperFunctionB() {}
void SomeHelperFunctionC() {}
//etc...
class SomeClass //<---
{
//Impl
};
}
Run Code Online (Sandbox Code Playgroud)
SomeHelperFunction[A-Z]是只在该翻译单元中需要的功能,所以我理解为什么他们是匿名的namespace.类似地,SomeClass也仅在该翻译单元中需要,但我的印象是,如果您没有全局类声明(例如,in),您可以在不同的翻译单元中具有相同名称的类,而不会出现任何类型的命名冲突一个通常包含的头文件).
我还要提到的是这个特定的翻译单元并没有包括可能声明一个类具有相同名称(任何头SomeClass).
那么,根据这些信息,有人可以说明为什么原来的程序员可能会这样做吗?也许只是作为未来的预防措施?
老实说,我以前从未见过匿名命名空间中使用过的类.
谢谢!
当匿名命名空间在全局级别应用时,它就像静态关键字一样.
匿名命名空间使它无法从另一个文件中调用命名空间内的任何内容.
匿名命名空间允许您仅限制当前文件的范围.
程序员可以这样做以避免命名冲突.在链接时,没有全球名称会以这种方式发生冲突.
例:
文件:test.cpp
namespace
{
void A()
{
}
void B()
{
}
void C()
{
}
}
void CallABC()
{
A();
B();
C();
}
Run Code Online (Sandbox Code Playgroud)
文件:main.cpp
void CallABC();//You can use ABC from this file but not A, B and C
void A()
{
//Do something different
}
int main(int argc, char** argv)
{
CallABC();
A();//<--- calls the local file's A() not the other file.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以上将编译好.但是,如果您尝试CallABC()在主体中编写函数,则会出现链接错误.
通过这种方式,你不能打电话A(),B()而且C()功能独立,但你可以叫CallABC()会叫所有的人一前一后.
你可以CallABC()在main.cpp中转发声明并调用它.但是你不能在main.cpp中转发声明test.cpp的A(),B()和C(),因为你会有一个链接错误.
至于为什么命名空间内有一个类.这是为了确保没有外部文件使用此类..cpp中的某些东西可能使用该类.