Is it OK to specify a duplicate C++ class scope? [

2019-04-06 05:34发布

Possible Duplicate:
Why are redundant scope qualifications supported by the compiler, and is it legal?

I wouldn't expect this to compile but it does. Could this be a compiler bug, or does it have some correct meaning?

$ 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

标签: c++ g++
1条回答
叼着烟拽天下
2楼-- · 2019-04-06 06:10

Yes, it's legal. A class's name is inserted into its own namespace, which is called the injected-class-name. From 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.

Note that Log::Log names the class constructor, which is only allowed in certain contexts, but as long as you end the chain of Log::Log::... with something other than Log (such as fn), then it doesn't name the constructor. Specifically, §3.4.3.1/1a says:

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.

查看更多
登录 后发表回答