当结构开头的名称与结构结尾的名称不同时,这是什么意思?例如:
struct book{
char title[50];
int year;
}boo;
或者例如
typedef struct book{
char title[50];
int year;
}boo;
答案 0 :(得分:3)
此示例
struct book{
char title[50];
int year;
}boo;
创建一个名为boo
的变量,其类型为struct book
。
另一个例子:
typedef struct book{
char title[50];
int year;
}boo;
将boo
定义为与struct book
(别名排序类型)相同的类型。
答案 1 :(得分:3)
在第一种情况下,您定义一个结构并立即创建其类型的变量。
struct book{
char title[50];
int year;
}boo; // <== boo is already a variable, you can start using it; boo.year = 2019;
在第二个示例中,您输入typedef来说明'boo'声明现在与您的结构相同,因此您可以在以后使用该'boo'创建变量。在这种情况下,在结构声明时不会创建任何变量。
typedef struct book{
char title[50];
int year;
}boo;
boo a, b; // <== here you create variables
答案 2 :(得分:1)
struct book
是类型名称(例如int
或double
)。该类型由花括号之间的内容-{ char title[50]; int year; }
定义。在第一个代码段中,boo
被声明为类型struct book
的 object (变量)。
C允许您定义结构类型并在同一声明中声明该类型的对象。看到两个操作被分解可能是有道理的:
struct book { char title[50]; int year; }; // creates the *type* "struct book"
struct book boo; // declares a *variable* of type "struct book"
使用typedef
工具可以为类型创建同义词或别名-在这种情况下,typedef struct book { char title[50]; int year; } boo;
创建boo
作为struct book
的同义词。然后,您可以将对象创建为
boo b1; // b1 is type boo, which is a synonym for struct book.
同样,将其拆分可能会有所帮助:
struct book { char title[50]; int year; }; // creates the type "struct book"
typedef struct book boo; // makes boo an alias for type "struct book"
在struct book
中,book
是结构类型的标记名-使用它,您可以在定义类型后引用该类型,例如>
struct book b2;
void some_function( struct book b );
等
如果您写类似
struct { char title[50]; int year; } boo;
然后仅 boo
可以具有该类型-您无法声明相同类型的其他变量,因为无法再引用它。即使您重复输入:
struct { char title[50]; int year; } boo;
struct { char title[50]; int year; } b2;
boo
和b2
在技术上具有不同的类型,即使类型实现是相同的。
现在,如果您使用typedef工具,则可以省略标签名称:
typedef struct { char title[50]; int year } boo;
因为现在您使用 typedef
名称 boo
来引用该类型:
boo b2;
void some_function( boo b );
答案 3 :(得分:0)
当标识符(名称)出现在struct
之后时,它称为标签,并且组合的struct
和标识符将命名为类型。很简单,struct book
是一种类型;其名称为struct book
。
当标识符出现在结构声明的花括号后面时,它是一个单独的名称-它与结构没有直接联系。它的作用取决于它所在的较大的声明。要查看此内容,请考虑声明的一种形式是“ type name ;
”。例如,我们可以拥有:
int a;
char b;
struct foo c;
struct bar { float x, y, z; } d;
在每个变量中,a
,b
,c
和d
是要声明的对象的标识符,其前面的文本是类型名称。 struct foo
和struct bar { float x, y, z }
仅是复杂的类型名称,而不是单个单词。声明标识符时,我们可以使用所需的任何名称(遵循有关使用哪些字符以及保留名称等的常规规则。)
我们还可以在类型名称之前添加各种修饰符,例如:
extern int a;
static char b;
const struct foo c;
typedef struct bar { float x, y, z; } d;
上面的前三个也声明了对象。在第四,typedef
是特殊的。它说:“这不是声明对象;第四条声明中,“ d”是struct bar
的新名称。
通常使用typedef
为struct
做一个别名,别名与结构标签相同,如下所示:
typedef struct bar { float x, y, z; } bar;
但是,在C中对此没有要求。除非程序员编写使它们相同的typedef
,否则结构的名称与类型的别名是无关的。 (在C ++中,这是自动完成的;声明struct bar
会创建一个名为bar
的类型。在C中,结构标记与类型名称位于不同的名称空间中。)