是否可以指定重复的C ++类范围? [英] Is it OK to specify a duplicate C++ class scope?

查看:176
本文介绍了是否可以指定重复的C ++类范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

blockquote>



我不会希望这个编译,但它是。这是一个编译器错误,还是有一些正确的含义?

  $ 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


解决方案

是的,这是合法的。类的名称插入到它自己的命名空间中,它被称为 injected-class-name 。从C ++ 03§9/ 2:


[...]插入到类本身的范围内;这称为 inject-class-name
为了进行访问检查, injected-class-name 被视为公共成员名。


请注意, Log :: Log 命名类构造函数,它只允许在某些上下文中,但只要结束 Log :: Log :: ... 使用日志(如 fn ),那么它不会命名构造函数。具体来说,§3.4.3.1/ 1a说:


如果 nested-name-specifier code> C ,以及在 nested-name-specifier 之后指定的名称,
C ,是 C (第9节)的注入类名,而是认为名称的名称为
类构造函数 C 。这样的构造函数名称只能在类定义之外的构造函数定义
declarator-id 中使用。



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

解决方案

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.

这篇关于是否可以指定重复的C ++类范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆