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

后端 未结 4 1660
旧巷少年郎
旧巷少年郎 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:47

    The reason, as stated in your quote from Stroustrup, is historical. In C, you must always prefix the name of the struct with struct; the name of the struct (like the name of unions or enums) is called a tag, and lives in a completely different name space than other symbols. So things like:

    struct stat
    {
        //  ...
    };
    int stat( char const* filename, struct stat* buf );
    

    are perfectly legal. (The above is, in fact, part of Posix).

    In C++, the name of a class (declared with class, struct or union) or an enum is in the same namespace as everything else, and unlike in C, you can write things like:

    struct MyClass {};
    MyClass variableName;
    

    This would not be legal C. In C, the second line would have to be:

    struct MyClass variableName;
    

    The problem is that C++ needs to be able to use interfaces defined in C (like the Posix interface, above). So C++ defines some special rules to allow it: you can give a variable or a function and a class type the same name. When you do, the variable or function name has precedence, and hides the class name, except in "elaborated type specifiers" (i.e. class, struct, union or enum, followed by a symbol), where non-type names are ignored in the lookup.

提交回复
热议问题