gpt4 book ai didi

c - 什么是 'forward declaration' 以及 'typedef struct X' 和 'struct X' 之间的区别?

转载 作者:行者123 更新时间:2023-11-30 16:20:50 24 4
gpt4 key购买 nike

我是 C 编程初学者,我知道 struct 类型声明和 typedef 结构声明之间的区别。我发现一个答案说,如果我们定义一个struct,例如:

typedef struct { 
some members;
} struct_name;

然后,这就像为匿名结构提供别名(因为它没有标签名称)。所以它不能用于前向声明。我不知道前向声明意味着什么。

另外,我想知道以下代码:

typedef struct NAME { 
some members;
} struct_alias;

NAMEstruct_alias 之间有什么区别吗?或者两者都相等struct_alias 是 struct NAME 的别名吗?

此外,我们可以声明一个 struct NAME 类型的变量,如下所示:

struct_alias variable1;

和/或类似:

struct NAME variable2;

或类似:

NAME variable3; 

最佳答案

当您需要循环结构声明时,

struct 前向声明会很有用。示例:

struct a {
struct b * b_pointer;
int c;
};

struct b {
struct a * a_pointer;
void * d;
};

当声明struct a时,它还不知道struct b的规范,但您可以转发引用它。

当您键入匿名结构时,编译器将不允许您在 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++

关于c - 什么是 'forward declaration' 以及 'typedef struct X' 和 'struct X' 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55141452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com