c++ - 一个类的成员可以被命名为与其类型(另一个类)相同的名称吗?

标签 c++ g++ implementation clang visual-c++-2012

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

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/

相关文章:

c++ - 使用 G++ 编译时出现 "Undefined Refrence to Foo"

machine-learning - kNN 最先进的实现

java - 使用 LinkedList Java 的空中交通管制程序出现问题

javascript - 我怎样才能做一个精确图像形状的鼠标悬停?

发现 C++ 正则表达式子字符串错误模式

linux - 找不到子文件夹中的 header

c++ - 没有这样的运算符 "[]"匹配这些操作数

c++ - 针对 libstdc++.so.5 进行编译未找到符号 @GLIBCPP_3.2

c++ - 如何使用windows api更改任务栏中的图标

c++ - C++ 查询中的获取和设置函数