如果有人可以详细解释,这两个声明之间有什么区别:
typedef struct atom {
int element;
struct atom *next;
};
Run Code Online (Sandbox Code Playgroud)
和
typedef struct {
int element;
struct atom *next;
} atom;
Run Code Online (Sandbox Code Playgroud)
Gan*_*har 14
这个是正常的 structure declaration
struct atom {
int element;
struct atom *next;
}; //just declaration
Run Code Online (Sandbox Code Playgroud)
的制作 object
struct atom object;
Run Code Online (Sandbox Code Playgroud)
struct atom {
int element;
struct atom *next;
}object; //creation of object along with structure declaration
Run Code Online (Sandbox Code Playgroud)
和
这是类型定义 struct atom类型
typedef struct atom {
int element;
struct atom *next;
}atom_t; //creating new type
Run Code Online (Sandbox Code Playgroud)
这atom_t是别名struct atom
创造对象
atom_t object;
struct atom object; //both the ways are allowed and same
Run Code Online (Sandbox Code Playgroud)
Bar*_*mar 13
目的typedef是为类型规范指定名称.语法是:
typedef <specification> <name>;
Run Code Online (Sandbox Code Playgroud)
完成后,您可以<name>像使用该语言的任何内置类型一样使用它来声明变量.
在你的第一个例子中,你<specification>就是一切都在开始struct atom,但<name>在它之后就没有了.所以你没有为类型规范赋予新名称.
在struct声明中使用名称与定义新类型不同.如果要使用该名称,则必须始终在其前面加上struct关键字.所以如果你宣布:
struct atom {
...
};
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令声明新变量:
struct atom my_atom;
Run Code Online (Sandbox Code Playgroud)
但你不能简单地宣布
atom my_atom;
Run Code Online (Sandbox Code Playgroud)
对于后者,你必须使用typedef.
请注意,这是C和C++之间的显着差异之一.在C++中,声明struct或class类型的确让你在变量声明使用它,你不需要typedef.typedef对于其他复杂类型的构造,例如函数指针,它在C++中仍然很有用.
你可能应该查看相关侧栏中的一些问题,它们解释了这个主题的一些其他细微差别.