c++ - 可以指定重复的 C++ 类作用域吗?

标签 c++ g++

<分区>

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.

关于c++ - 可以指定重复的 C++ 类作用域吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12843893/

相关文章:

compiler-errors - 有些人在gcc中定义了编译成功,但是g++失败了

c++ - 为什么能找到stdint.h而找不到cstdint?

c++ - 如何使用循环增加指数?

c++ - 这些辅助文件应该在 Git 版本控制之下吗?

c++ - 将 C++ 编译成 "real"程序

c++ - 返回带有模板化类的类成员结构

c++ - 我的类的可变参数模板构造函数不能修改我的类成员,为什么会这样?

c++ - 模板化虚函数是不可能的。只是暂时的技术限制?

C++使用数组设置交集和并集

c++ - std::tuple 与多个空成员的比较不会在 GCC 上编译