考虑一下这段 C++ 代码:
namespace
{
void f()
{
}
class A
{
void f()
{
::f(); // VC++: error C2039: 'f' : is not a member of '`global namespace''
}
};
}
GCC 编译得很好。 Visual C++ 2008 编译失败,出现 C2039 错误。这两个编译器中的哪一个在这里是正确的?有什么方法可以正确引用 "global" f
吗?
编辑: Zack 建议尝试一下,它适用于两种编译器。我觉得有点奇怪。
namespace
{
void f()
{
}
class A
{
void f();
};
}
void A::f()
{
::f();
}
最佳答案
VC++ 2008 在这里是错误的。根据c++03标准3.4.3.4:
A name prefixed by the unary scope operator :: (5.1) is looked up in global scope, in the translation unit where it is used. The name shall be declared in global namespace scope or shall be a name whose declaration is visible in global scope because of a using-directive (3.4.3.2). The use of :: allows a global name to be referred to even if its identifier has been hidden (3.3.7).
这里的重要部分是全局命名空间中的 using 指令将使这些符号可以通过范围运算符访问。
并且根据 7.3.1.1/1,匿名命名空间相当于:
namespace *unique* { /* empty body */ }
using namespace *unique*;
namespace *unique* { namespace-body }
所以在这两个部分之间,独立函数应该可以在全局命名空间中访问。
关于c++ - 如何正确引用匿名命名空间中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5503901/