【问题标题】:Regarding forward declaration in c关于c中的前向声明
【发布时间】:2017-05-20 11:44:20
【问题描述】:
typedef struct treeNodeListCell {
    treeNode *node;
    struct treeNodeListCell *next;
}treeNodeListCell;

typedef struct treeNode{

    imgPos position;
    treeNodeListCell *next_possible_positions;

}treeNode;


typedef struct segment{
    treeNode *root;
}Segment;

我对上面结构的前向声明感到很困惑,如何使用当前声明?

【问题讨论】:

    标签: c struct forward-declaration


    【解决方案1】:

    因此,从您的示例代码中,我了解到您希望将 typedefs 用于您的 structs 并且您需要前向声明。最直接(原文如此)的方式是这样的:

    typedef struct treeNode treeNode;
    typedef struct treeNodeListCell treeNodeListCell;
    typedef struct segment segment;
    
    struct treeNodeListCell {
        treeNode *node;
        treeNodeListCell *next;
    };
    
    struct treeNode {
        imgPos position;
        treeNodeListCell *next_possible_positions;
    };
    
    struct segment {
        treeNode *root;
    };
    

    使用比 更旧的标准时要小心。在这种情况下,不允许重复 typedef,因此不同标头中的任何前向声明都必须如下所示

    struct treeNode;
    

    然后使用struct treeNode而不是treeNode来引用类型。

    有了,这个限制终于没有了,如果定义的类型相同,你可以重复typedef

    【讨论】:

      【解决方案2】:

      你应该写

      typedef struct treeNodeListCell {
          struct treeNode *node;
          ^^^^^^^^^^^^^^^
          struct treeNodeListCell *next;
      }treeNodeListCell;
      

      在这种情况下,类型名称 struct treeNode 是前向声明的。

      如果声明看起来像

      typedef struct treeNodeListCell {
          treeNode *node;
          ^^^^^^^^
          struct treeNodeListCell *next;
      }treeNodeListCell;
      

      那么编译器就无法知道treeNode是什么意思。

      【讨论】:

      • 但是struct treeNode此时还没有声明,不是吗?
      • @KeineLust 不,它已声明但它是不完整的类型。
      猜你喜欢
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      相关资源
      最近更新 更多