c中的自引用结构

  • 本文关键字:结构 自引用 c struct
  • 更新时间 :
  • 英文 :


我正在尝试将一些在VS2010中编译C++良好的代码移动到c(gcc c99),并且出现编译错误。它与其他自引用结构问题略有不同,因为我有 2 个用户定义类型,每个类型都包含指向彼此的指针。看来我的前瞻声明还不够。

struct potato; //forward declare both types
struct tomato;
struct potato
{
potato* pPotato; //error: unknown type name ‘potato’
tomato* pTomato;
};
struct tomato
{
potato* pPotato;
tomato* pTomato;
};

为什么这在 gcc 99 中不起作用?为什么它可以作为C++代码?我应该如何修改它以获得与 c99 相同的行为?

或者,将它们typedef

typedef struct potato potato; //forward declare both types
typedef struct tomato tomato;
struct potato
{
potato* pPotato;
tomato* pTomato;
};
struct tomato
{
potato* pPotato;
tomato* pTomato;
};

自引用类型在 C 中有效,但在 C 中,struct与变量/常量位于不同的命名空间中,并且在使用其名称时必须以struct为前缀。

此外,请避免使用匈牙利表示法,在您的情况下是p前缀。

试试这个:

struct potato; //forward declare both types
struct tomato;
struct potato
{
struct potato* potato;
struct tomato* tomato;
};
struct tomato
{
struct potato* potato;
struct tomato* tomato;
};

避免不断键入struct foo的传统方法是使用typedef

typedef struct potato potato;

struct potato的定义可以匿名和内联使用:

typedef struct { ... } potato;

我个人观察到,typedef struct的使用似乎正在减少,使用"手写"形式,在使用时始终指定struct,这又重新流行起来。

你需要

struct potato
{
struct potato* pPotato;
struct tomato* pTomato;
};

纯 C 不会自动 typedef 结构。

就个人而言,我喜欢自动类型定义(我使用一个简短的posfix来传达typedef是一个结构体),所以我一直在用宏模拟它:

#define Struct(Nam,...) typedef struct Nam Nam; struct Nam __VA_ARGS__
Struct(tomato,);
Struct(potato,);
Struct( potato, {
potato* pPotato; //error: unknown type name ‘potato’
tomato* pTomato;
});
Struct(tomato, {
potato* pPotato;
tomato* pTomato;
});
tomato tom;
potato pot;

最新更新