Possible Duplicate:
Why are redundant scope qualifications supported by the compiler, and is it legal?
我不希望它能编译,但它确实编译了。这可能是编译器错误,还是它有一些正确的含义?
$ g++ -c scopes.cpp
$ cat scopes.cpp
class Log {
public:
Log() { }
static void fn() { }
};
void test() {
Log::Log::Log::Log::Log::Log::fn();
}
$ g++ --version
g++ (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3
是的,这是合法的。一个类的名称被插入到它自己的 namespace 中,称为注入(inject)类名称。来自 C++03 §9/2:
[...] The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name.
For purposes of access checking, the injected-class-name is treated as if it were a public member name.
请注意,Log::Log
命名了类构造函数,这仅在某些上下文中允许,但只要您结束 Log::Log::...
使用 Log
以外的东西(例如 fn
),那么它不会命名构造函数。具体来说,§3.4.3.1/1a 说:
If the nested-name-specifier nominates a class C
, and the name specified after the nested-name-specifier,
when looked up in C
, is the injected-class-name of C
(clause 9), the name is instead considered to name the
constructor of class C
. Such a constructor name shall be used only in the declarator-id of a constructor definition
that appears outside of the class definition.