c语言中的自引用结构 我试图把一些编译成C++的代码在VS2010中移到C(GCC C99),我会得到编译错误。它与其他自引用结构问题略有不同,因为我有两个用户定义的类型,每个类型都包含指向彼此的指针。看来我的远期申报还不够 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; };

c语言中的自引用结构 我试图把一些编译成C++的代码在VS2010中移到C(GCC C99),我会得到编译错误。它与其他自引用结构问题略有不同,因为我有两个用户定义的类型,每个类型都包含指向彼此的指针。看来我的远期申报还不够 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; };,c,struct,C,Struct,为什么这在gcc 99中不起作用?为什么它可以作为C++代码?我应该如何修改它以获得与c99相同的行为 struct potato { struct potato* pPotato; struct tomato* pTomato; }; 普通C不会自动键入def结构 就我个人而言,我喜欢自动类型定义(我使用一个简短的posfix来表示typedef是一个struct),所以我一直在用宏模拟它: #define Struct(Nam,...) typedef struct Na

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

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

};
普通C不会自动键入def结构

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

#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;

自引用类型在C中有效,但在C
struct
s中,它与变量/常量位于不同的命名空间中,并且在使用它们的名称时必须以
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
的“速记”形式又重新流行起来。

或者,
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;
};

错误是什么?编辑以显示错误行如果我还想包含一个typedef,那么我不必修改前面有很多土豆和西红柿但没有“struct”的代码的其余部分呢?@user2864293我个人使用一个宏,在每个struct定义中预先添加typedef。我已经在答案中添加了它。这依赖于gcc扩展(不允许任何参数匹配
,…
)@M.M在转发声明中添加了逗号。(事实上,我以前从未用它来转发声明。我只是用它来定义一个typedef自动前缀)。匈牙利符号现在不受欢迎吗?您为什么建议避免使用它?@user2864293因为它会妨碍可读性,并且不会提供任何有用的信息。你的编译器和IDE知道了什么类型,所以你可以通过鼠标指针在名称上悬停来获取更多信息。@ USER 82693,它也阻碍了可维护性:如果你使用C++并有一个原始指针,决定将它改为智能指针,那么你就必须重命名你的代码> P<代码>和<代码> PTR < /代码>。前缀在任何地方都可以使用。我认为它应该在没有转发声明的情况下工作。