Can a member of a class be named the same name as its type (another class)?

前端 未结 3 1943
半阙折子戏
半阙折子戏 2020-12-20 12:50

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

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

As you

相关标签:
3条回答
  • 2020-12-20 13:26

    gcc is correct, from [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.

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

    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;
    };
    
    0 讨论(0)
  • 2020-12-20 13:26

    @JesseGood provide a complete answer, but if you really want to do this without any error, you can use type's full name and it will work as follow:

    struct S {};
    struct T { ::S S; };
    int main() {return 0;}
    

    No there is no error, since S in your class is T::S and its type is ::S!

    0 讨论(0)
  • 2020-12-20 13:43

    This code is ill-formed, no diagnostic required. Like the diagnostic says, if a declaration uses a name and the name has a different meaning than it would have when looked up at the end of the class definition, the programm is illformed, no diagnostic required.

    0 讨论(0)
提交回复
热议问题