尝试在不同的编译器上编译以下代码会得到两个不同的结果:
struct S{};
struct T{S S;};
int main(){}
如您所见,在 T
中,我有一个与之前定义的类 S
同名的对象。
在 GCC 4.7.2 上,I get the following error 属于 S S;
T
内的声明:
error: declaration of 'S T::S' [-fpermissive]
error: changes meaning of 'S' from 'struct S' [-fpermissive]
但是,将其移出类(或移入 main
)works fine :
struct S{};
S S;
int main(){}
它给我的错误到底是什么意思?
在 Visual Studio 2012 中,整个编译和运行没有任何错误。将它粘贴到 this Clang 3.0 compiler 中也不会出现错误。
哪个是对的?我真的可以这样做吗?
最佳答案
gcc 是正确的,来自[3.3.7 Class Scope]
A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.
但是,请注意不需要诊断
,因此所有编译器都符合标准。
原因在于类作用域的工作方式。当您编写 S S;
时,S
在整个 类中可见,并且在您使用 S
时会改变含义。
struct S{};
struct T{
void foo()
{
S myS; // Not possible anymore because S refers to local S
}
S S;
};
关于c++ - 一个类的成员可以被命名为与其类型(另一个类)相同的名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12943607/