什么是“前向声明"以及“typedef struct X"和“struct X"之间的区别? [英] What is 'forward declaration' and the difference between 'typedef struct X' and 'struct X'?
问题描述
我是 C 编程的初学者,我知道 struct
类型声明和 typedef
结构声明之间的区别.我偶然知道一个答案说,如果我们定义一个 struct
像:
I am a beginner in C programming and I know the difference between struct
type declaration and typedef
struct declaration. I came across to know an answer saying that if we define a struct
like:
typedef struct {
some members;
} struct_name;
然后就像为匿名结构提供别名(因为它没有标签名称).所以它不能用于前向声明.我不知道前向声明是什么意思.
Then it will be like providing an alias to an anonymous struct (as it is not having a tag name). So it can't be used for forward declaration. I don't know what the forward declaration means.
另外,我想知道以下代码:
Also, I wanted to know that for the following code:
typedef struct NAME {
some members;
} struct_alias;
NAME
和 struct_alias
之间有什么区别吗?或者两者都等于struct_alias
是 struct NAME 的别名?
Is there any difference between NAME
and struct_alias
? Or are both equal as
struct_alias
is an alias of struct NAME ?
此外,我们可以像这样声明一个 struct NAME
类型的变量:
Furthermore, can we declare a variable of type struct NAME
like these:
struct_alias variable1;
和/或喜欢:
struct NAME variable2;
或喜欢:
NAME variable3;
推荐答案
struct
前向声明在您需要循环结构声明时非常有用.示例:
struct
forward declarations can be useful when you need to have looping struct declarations. Example:
struct a {
struct b * b_pointer;
int c;
};
struct b {
struct a * a_pointer;
void * d;
};
当声明 struct a
时,它还不知道 struct b
的规范,但你可以向前引用它.
When struct a
is declared it doesn't know the specs of struct b
yet, but you can forward reference it.
当您 typedef 一个匿名结构时,编译器将不允许您在 typedef 之前使用它的名称.
When you typedef an anonymous struct then the compiler won't allow you to use it's name before the typedef.
这是非法的:
struct a {
b * b_pointer;
int c;
};
typedef struct {
struct a * a_pointer;
void * d;
} b;
// struct b was never declared or defined
这虽然是合法的:
struct a {
struct b * b_pointer;
int c;
};
typedef struct b {
struct a * a_pointer;
void * d;
} b;
// struct b is defined and has an alias type called b
也是这样:
typedef struct b b;
// the type b referes to a yet undefined type struct b
struct a {
b * struct_b_pointer;
int c;
};
struct b {
struct a * a_pointer;
void * d;
};
还有这个(仅在 C 中,在 C++ 中非法):
typedef int b;
struct a {
struct b * struct_b_pointer;
b b_integer_type;
int c;
};
struct b {
struct a * a_pointer;
void * d;
};
// struct b and b are two different types all together. Note: this is not allowed in C++
这篇关于什么是“前向声明"以及“typedef struct X"和“struct X"之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!