Difference between 'struct' and 'typedef struct' in C++?

前端 未结 8 1624
忘了有多久
忘了有多久 2020-11-21 06:12

In C++, is there any difference between:

struct Foo { ... };

and:

typedef struct { ... } Foo;
8条回答
  •  温柔的废话
    2020-11-21 06:28

    There is a difference, but subtle. Look at it this way: struct Foo introduces a new type. The second one creates an alias called Foo (and not a new type) for an unnamed struct type.

    7.1.3 The typedef specifier

    1 [...]

    A name declared with the typedef specifier becomes a typedef-name. Within the scope of its declaration, a typedef-name is syntactically equivalent to a keyword and names the type associated with the identifier in the way described in Clause 8. A typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration (9.1) or enum declaration does.

    8 If the typedef declaration defines an unnamed class (or enum), the first typedef-name declared by the declaration to be that class type (or enum type) is used to denote the class type (or enum type) for linkage purposes only (3.5). [ Example:

    typedef struct { } *ps, S; // S is the class name for linkage purposes
    

    So, a typedef always is used as an placeholder/synonym for another type.

提交回复
热议问题