快速问题,如何前向声明以下的
treeNodeListCell
结构体。
你不需要这样做。
首先,你必须区分通过标签识别结构类型和通过
typedef
定义的别名来识别它们。特别是,你需要明白
typedef
是完全可选的。当你使用它来定义结构类型的别名时,将
typedef
声明与结构声明分开可能更清晰。
以下是没有任何
typedef
的声明:
struct _treeNode {
struct _treeNodeListCell *next_possible_positions;
};
struct _treeNodeListCell {
struct _treeNode *node;
struct _treeNodeListCell *next;
};
使用struct <tag>
形式表达的结构类型不需要前向声明。
您也可以添加typedef。通过添加typedef
关键字和一个或多个标识符,它们可以与上面的定义相关联,或者可以单独编写,就像我之前推荐的那样:
typedef struct _treeNode treeNode;
typedef struct _treeNodeListCell treeNodeListCell;
个人认为,typedefs 被过度使用了。我通常不会为我的结构体和联合体类型定义 typedef
别名。
但是如果你真的想这样做,那么你可以声明一个未完成的类型的 typedef,比如一个尚未定义的结构体类型。这是一个常规声明,而不是前向声明,但它将允许您在结构体的定义中使用别名,这应该是您的目标:
typedef struct _treeNode treeNode;
typedef struct _treeNodeListCell treeNodeListCell;
struct _treeNode {
treeNodeListCell *next_possible_positions;
};
struct _treeNodeListCell {
treeNode *node;
treeNodeListCell *next;
};
事实上,从C11开始,您可以在同一作用域中写入同一
typedef
名称的多个声明,只要它们都定义了该名称以标识相同的类型。可以利用此规定来允许编译问题中提供的typedef /结构声明。请注意,指定相同类型不需要以相同方式
表达该类型。由于这应该是一项练习,我将让您解决剩下的几个细节。
_treeNodeListCell
,它被typedef为treeNodeListCell
。你确定这不是一个错误吗? - Rahul Bharadwaj