简体   繁体   English

循环结构声明C.

[英]Circular structure declaration C

I have to declare a structure that depends on another structure declaration, but gcc keeps complaining and I've reached a point where I can't work around it by simply moving the code around. 我必须声明一个依赖于另一个结构声明的结构,但gcc一直在抱怨,我已经达到了一个我无法通过简单地移动代码来解决它的问题。 Here's the deal: 这是交易:

typedef struct inodes
{
    unsigned short int  numInode;
    ListaBlocos         *blocos;
    ListaInodes         *filhos;
    Meta                metaDados;
    unsigned short int  tempo;
} Inode;


typedef struct listablocos
{
    Bloco               bloco;
    struct listablocos  *prox;
} ListaBlocos;

typedef struct listainodes
{
    Inode               inode;
    struct listainodes  *prox;
} ListaInodes;

Basically, ListaInodes is a list that has instances of the Inode type in it. 基本上,ListaInodes是一个包含Inode类型实例的列表。 So I'd have to declare Inode before it. 所以我必须在它之前声明Inode。 But if I do, gcc will complain with this: 但如果我这样做,gcc会抱怨这个:

error: unknown type name 'ListaInodes'

because one of the fields of Inode is a list of other Inodes. 因为Inode的一个字段是其他Inode的列表。 How can this be fixed, preferrably with not too drastic changes to the code? 如何修复,最好不要对代码进行太大的修改?

Just add the typedef before the definition. 只需在定义之前添加typedef

typedef struct listainodes ListaInodes;
typedef struct inodes Inode;
typedef struct listablocos ListaBlocos;

struct inodes
{
    unsigned short int  numInode;
    ListaBlocos         *blocos;
    ListaInodes         *filhos;
    Meta                metaDados;
    unsigned short int  tempo;
};

struct listablocos
{
    Bloco         bloco;
    ListaBlocos  *prox;
};

struct listainodes
{
    Inode        inode;
    ListaInodes *prox;
};

As you can see you can even define the struct s in the implementation file instead of the header, thus hiding the structure definition from the potential structure users, adding accessor get/set like functions, you can add functionality while the struct is effectively hidden, a very common technique with numerous benefits, like avoiding the misuse of a given struct field. 如您所见,您甚至可以在实现文件中定义struct而不是标头,从而将结构定义隐藏在潜在的结构用户中,添加访问器get / set就像函数一样,您可以在struct被有效隐藏时添加功能,一种非常常见的技术,有许多好处,例如避免滥用给定的struct域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM