℡Wang Yan 2009-03-04 20:41 采纳率: 100%
浏览 208
已采纳

C + + 中'struct'和'typedef struct'的区别?

In C++, is there any difference between:

struct Foo { ... };

and

typedef struct { ... } Foo;

转载于:https://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c

  • 写回答

8条回答 默认 最新

  • 狐狸.fox 2009-03-04 20:45
    关注

    In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.

    The C language standard (C89 §3.1.2.3, C99 §6.2.3, and C11 §6.2.3) mandates separate namespaces for different categories of identifiers, including tag identifiers (for struct/union/enum) and ordinary identifiers (for typedef and other identifiers).

    If you just said:

    struct Foo { ... };
    Foo x;
    

    you would get a compiler error, because Foo is only defined in the tag namespace.

    You'd have to declare it as:

    struct Foo x;
    

    Any time you want to refer to a Foo, you'd always have to call it a struct Foo. This gets annoying fast, so you can add a typedef:

    struct Foo { ... };
    typedef struct Foo Foo;
    

    Now struct Foo (in the tag namespace) and just plain Foo (in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type Foo without the struct keyword.


    The construct:

    typedef struct Foo { ... } Foo;
    

    is just an abbreviation for the declaration and typedef.


    Finally,

    typedef struct { ... } Foo;
    

    declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also cannot be forward-declared. If you want to make a forward declaration, you have to give it a name in the tag namespace.


    In C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name. See Michael Burr's answer for the full details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系