Typedef-name conflicts with struct tag in C++

前端 未结 1 880
难免孤独
难免孤独 2020-12-18 12:25

This is my second investigation about structure declaration in C++. (The first is here) But now I came across this post. Specifically I am not sure why this is perfectly fin

相关标签:
1条回答
  • 2020-12-18 12:39

    In C++, you cannot use struct myStruct to refer to a tagless structure which has been typedefed. And you cannot define a different struct myStruct, because the name collides with the typedef name.

    If you add the tag, then both struct myStruct and myStruct alone will refer to the type, in both C and C++:

    typedef struct myStruct {
        int one;
        int two;
    } myStruct;
    

    Here there is no collision in C++ because the name resolves to just one type, and this is specifically allowed by a special rule. C++ Standard section 7.1.3 includes the following rules:

    In a given non-class scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers.

    If a typedef specifier is used to redefine in a given scope an entity that can be referenced using an elaborated-type-specifier, the entity can continue to be referenced by an elaborated-type-specifier or as an enumeration or class name in an enumeration or class definition respectively.

    In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in that scope to refer to a different type.

    Similarly, in a given scope, a class or enumeration shall not be declared with the same name as a typedef-name that is declared in that scope and refers to a type other than the class or enumeration itself.

    [ Note: A typedef-name that names a class type, or a cv-qualified version thereof, is also a class-name (9.1). If a typedef-name is used to identify the subject of an elaborated-type-specifier (7.1.6.3), a class definition (Clause 9), a constructor declaration (12.1), or a destructor declaration (12.4), the program is ill-formed. — end note ]

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