一个类的成员可以被命名为与其类型(另一个类)相同的名称吗? [英] Can a member of a class be named the same name as its type (another class)?

查看:371
本文介绍了一个类的成员可以被命名为与其类型(另一个类)相同的名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在不同的编译器上编译下面的代码给我两个不同的结果:

Trying to compile the following code on different compilers gives me two different results:

struct S{};
struct T{S S;};
int main(){}

正如你所看到的, T ,我有一个与之前定义的类 S 相同的对象。

As you can see, inside T, I have an object named the same as the previously defined class S.

在GCC 4.7.2上,我收到以下错误, code> $

On GCC 4.7.2, I get the following error pertaining to the S S; declaration inside T:


错误:声明'ST :: S'[-fpermissive]

错误:从'struct S'改变'S'的意义[-fpermissive]

error: declaration of 'S T::S' [-fpermissive]
error: changes meaning of 'S' from 'struct S' [-fpermissive]

但是,将它移出类(或 main 工作正常

However, moving it outside of the class (or into main) works fine:

struct S{};
S S;
int main(){}

它给我的错误是什么意思?

What exactly does it mean by the error it's giving me?

在Visual Studio 2012中,整个编译和运行没有任何错误。将它粘贴到这个Clang 3.0编译器中也没有错误。

In Visual Studio 2012, the whole thing compiles and runs without any errors. Pasting it into this Clang 3.0 compiler gives me no errors as well.

哪个是对的?

推荐答案

gcc是否正确,来自[3.3.7类范围]

gcc is correct, from [3.3.7 Class Scope]


在类S中使用的名称N,在其
上下文中引用相同的声明,并在S的完成范围内重新求值。如果违反此规则,则不需要
诊断。

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.

但是,请注意是必需的,因此所有编译器都符合。

However, note that no diagnostic is required, so all compilers are conforming.

原因是因为类范围工作原理。当您在整个类别中显示 SS; S 您使用 S

The reason is because of how class scope works. When you write S S; S is visible within the entire class and changes the meaning when you use S.

struct S{};
struct T{
    void foo()
    { 
        S myS; // Not possible anymore because S refers to local S
    }
    S S;
};

这篇关于一个类的成员可以被命名为与其类型(另一个类)相同的名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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