Why are structures typedef'ed to their own names?
本问题已经有最佳答案,请猛点这里访问。
在代码的许多地方,我都看到过这样的代码:
1 2 3 | typedef struct Name_of_Struct{ //Things that the struct holds } Name_of_Struct; |
我好像不明白为什么要这样做?为什么结构
在C++中,你不必这样做。
但是在C语言中,这样做是为了保存一些输入
1 2 3 4 5 | 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
1 2 3 4 5 | 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中使用了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // 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; |
似乎有些程序员已经将这两种方法结合起来了。
代码可能在C和C++之间共享。C编程语言不会自动为用户创建的类型(例如,