繁体   English   中英

在不阻止关键字struct的情况下,对结构进行typedef

[英]typedef a struct without preventing the keyword struct

假设此方案:

/* avl.c */

typedef struct avl {
    void *data;
    int height;
    struct avl *left, *right;
} node;

/* avl.h */

struct avl; /* opaque */

我要使用:

struct node *root;

代替

node *root;

在avl.c中,但目前我发现的最好结果是:

struct avl {
    void *data;
    int height;
    struct avl *left, *right;
};

#define node avl

其他方式?

然后,您应该删除typedef

struct node{
    void *data;
    int height;
    struct node *left, *right;
} 

在不使用预处理器的情况下,必须给struct和typedef使用相同的名称,例如,

  typedef struct node {
        void *data;
        int height;
        struct node *left, *right;
    } node;

所以现在struct nodenode是同一回事。

除了使用宏之外,别无其他方法。 原因是struct标记具有自己的名称空间 标记名称空间中的不同名称始终引用不同的类型,即使结构包含相同的成员类型。 正确的类型别名只能使用typedef定义,typedef被定义为别名而不是单独的类型。

struct avl {
    void *data;
    int height;
    struct avl *left, *right;
};

typedef struct alv node;

struct avl* ptr1; //valid
avl* ptr1; //not valid
struct node* ptr2;  //valid
node* ptr3;  //also valid

那会迫使您使用struct avl ,而不会强迫您使用struct node ,但是如果您愿意的话,也可以。

暂无
暂无

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

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