为什么结构被类型化为自己的名称?



在代码的许多地方,我都看到过这样的代码:

typedef struct Name_of_Struct{
    //Things that the struct holds
} Name_of_Struct;

我似乎不明白为什么要发表这样的声明?为什么结构体typedef'被附加到自己的名称?这不是说typedef Name_of_struct Name_of_Struct;吗?我知道这样的声明背后一定有一些原因,因为这样的代码实例可以在像SDL这样良好且高度使用的代码库中看到。

在C++中,您不必执行

然而,在C中,这样做是为了节省一些键入

struct Name_of_Struct{
    //Things that the struct holds
} ;
struct Name_of_Struct ss; // If not typedef'ed you'll have to use `struct`

但使用typedef

typedef struct Name_of_Struct{
    //Things that the struct holds
} Name_of_Struct;
Name_of_Struct ss ; // Simply just use name of struct, avoid struct everywhere

代码可能在C和C++之间共享。C编程语言不会自动为用户创建的类型(例如,enumstructunion)创建类型名称。最近几年我没有写过很多C,所以C99可能已经改变了这一点。

指定两次名称是多余的。

最初在C中使用typedef,所以您不需要一直使用struct来限定名称。在C++中,您可以简单地将struct命名。

// C method
struct MyStruct {};
// need to qualify that name with `struct`
struct MyStruct s;
// C method avoiding typing `struct` all the time
typedef struct {} MyStruct;
MyStruct s; // no need to use `struct`
// C++ way
struct MyStruct {};
MyStruct s;

似乎有些程序员把这两种方法搞得像个弗兰肯斯坦。

最新更新