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

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

问题描述

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

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 上,我收到以下与 SS; 声明有关的错误T:

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

错误:S T::S"的声明 [-fpermissive]
错误:从 'struct S' [-fpermissive] 更改 'S' 的含义

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

但是,将其移出类(或移入 main)工作正常:p>

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.

哪个是对的?我真的可以这样做吗?

Which is right? Can I actually do this or not?

推荐答案

gcc是正确的,来自[3.3.7 Class Scope]

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天全站免登陆