Why is it possible to declare a struct and a non-struct with the same name?

后端 未结 4 1645
旧巷少年郎
旧巷少年郎 2021-01-03 00:11

Apparently,

For reasons that reach into the prehistory of C, it is possible to declare a struct and a non-struct with the same name in the same scope

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 00:30

    The reason it is like this has to do with C++ inheriting from C. It was not "added" to C++, it is there because it works that way in C.

    In C, you have to use struct X and union Y (there is no class keyword in C), or use typedef struct X A; and then use the name A instead of strcut X (where X and A could be the same name).

    In C++ the compiler will, as long as the name is unique, understand that X is referring to struct X. You don't have to type struct, union or class in front of the name, or use typedef to create a new, standalone name.

    Since C++ is designed to allow (wherever possible) the use of C syntax, it is still allowed to write struct X when referring to a struct. This allows the use of a name that is otherwise ambiguous.

    It is highly recommended to NOT make use of this "possibility" unless required by historical design decisions, because all it will achieve is more confusion...

提交回复
热议问题