2014-09-28 86 views
1

在代码中的许多地方,我已经看到了这样的代码:为什么结构类型被定义为自己的名字?

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

我似乎不明白为什么这样的声明?为什么结构typedef'被修改为自己的名字?难道不是说typedef Name_of_struct Name_of_Struct;?我知道这样的声明背后必然有一些原因,因为这样的代码实例在SDL等良好和高度使用的代码库中被看到。

+0

请注意,SDL是一个C库,可以从C++中使用。 – Csq 2014-09-28 14:33:20

+0

首先,这是一个C特定的声明模式。 C,而不是C++。你将问题标记为[C++]。那么,你有没有在C++代码中看到它(这在共享的C/C++代码中是可行的)?或者你是否错误地提出了你的问题? – AnT 2014-09-28 14:36:19

+0

我不知道所有的代码都是c。对不起。 – 2014-09-28 14:40:41

回答

4

在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 
0

代码可能在C和C++之间共享。 C编程语言不会自动为用户创建的类型创建类型名称(例如,enum,structunion)。我近几年没有写很多C语言,所以在C99中可能会有所变化。

+0

只是好奇最初的投票来自哪里? – 2014-09-28 14:27:10

1

指定名义进行两次是多余的。

最初在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; 

看来有些程序员已经做了两种方法的科学怪人。

相关问题