typedef struct 起别名相对于struct 直接定义结构体有什么优点?

typedef struct 起别名相对于struct 直接定义结构体有什么优点?C++中,为什么一般见到的实现数据结构的代码都是用typedef struct为结构体起个别名,而不是直接struct定义一个结构体。这样有什么优点?为什么这样做?可不可以不这样做?

前者是C语言的(C++当然也兼容),后者是C++的。

编写代码和阅读代码更方便、统一,不易出错
可以不这样做,不是强制项

  • 看下这篇博客,也许你就懂了,链接:定义结构体 typedef struct 的用法总结
  • 同时,你还可以查看手册:c语言-struct 中的内容
  • 除此之外, 这篇博客: 结构体struct的定义和使用中的 🍊4、使用typedef, 定义结构体的同时为结构体取别名 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • typedef struct type_four_s {
        int a;
        int b;
    }type_four_alias_s;
    

    使用这种形式,定义了结构体type_four_s,并为结构体设置别名为type_four_alias_s,使用结构体名定义结构体变量时,C需要加struct,C++不需要;使用结构体别名定义结构体变量时,C和C++都不需要加struct

    C中:

    //使用结构体名定义结构体变量,需要加struct
    struct type_four_s type_four1 = {13,14};   
    //使用结构体别名定义结构体变量,不需要加struct   
    type_four_alias_s type_four2 = {15,16};      
    

    C++中:

    //使用结构体名定义结构体变量,不需要加struct
    type_four_s type_four1 = {13,14};     
    //使用结构体别名定义结构体变量,不需要加struct       
    type_four_alias_s type_four2 = {15,16};