[英]Can a class have a member that is another with the same name in the same namespace?
[英]Can a member of a class be named the same name as its type (another class)?
尝试在不同的编译器上编译以下代码给我两个不同的结果:
struct S{};
struct T{S S;};
int main(){}
如您所见,在T
,我有一个名为与先前定义的类S
相同的对象。
在GCC 4.7.2上, 我收到了与SS;
有关的以下错误 SS;
T
内的声明:
错误:'ST :: S'的声明[-fpermissive]
错误:从'struct S'改变'S'的含义[-fpermissive]
但是,将它移到课堂外(或main
) 可以正常工作 :
struct S{};
S S;
int main(){}
它给我的错误究竟是什么意思?
在Visual Studio 2012中,整个事件编译并运行没有任何错误。 将它粘贴到这个Clang 3.0编译器中也没有错误。
哪个是对的? 我真的可以这样做吗?
gcc是正确的,来自[3.3.7类范围]
在类S中使用的名称N应在其上下文中引用相同的声明,并在完成的S范围内重新评估。违反此规则不需要诊断。
但请注意, no diagnostic is required
,因此所有编译器都符合要求。
原因是因为课程范围如何运作。 当你写SS;
S
在整个类中可见,并在使用S
时更改含义。
struct S{};
struct T{
void foo()
{
S myS; // Not possible anymore because S refers to local S
}
S S;
};
此代码格式错误,无需诊断。 就像诊断所说的那样,如果一个声明使用了一个名称,并且该名称的含义与在类定义末尾查找时的含义不同,则该程序不正确,无需诊断。
@JesseGood提供了一个完整的答案,但是如果你真的想这样做而没有任何错误,你可以使用类型的全名,它将按如下方式工作:
struct S {};
struct T { ::S S; };
int main() {return 0;}
没有没有错误,因为S
在你的类是T::S
和它的类型是::S
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.