gpt4 book ai didi

c - 在 C 中是否可以一致地引用前向声明和非前向声明的结构?

转载 作者:行者123 更新时间:2023-11-30 16:51:52 24 4
gpt4 key购买 nike

这不适用于foo

struct Foo;

typedef struct
{
int x;
}
Bar;

void foo (Foo *); // unknown type name ‘Foo’

void bar (Bar *);

typedef struct
{
int y;
}
Foo;

这不适用于bar

struct Foo;

typedef struct
{
int x;
}
Bar;

void foo (struct Foo *);

void bar (struct Bar *); ‘struct Bar’ declared inside parameter list

typedef struct
{
int y;
}
Foo;

我的一些结构必须进行前向声明,因为它们作为指针传递,而其中一些结构必须不前向声明,因为它们作为值传递。

有没有一种方法可以在 C 中声明类型,以便所有函数原型(prototype)始终能够以相同的方式引用自定义类型,无论它们是否是前向声明的?

最佳答案

您的问题不是前向声明与非前向声明,而是 struct Xtypedef struct { ... } X

您可以仅使用struct X来解决这个问题:

struct Foo;

struct Bar
{
int x;
};

void foo (struct Foo *);
void bar (struct Bar *);

struct Foo
{
int y;
};

一旦你有了这个,你就可以引入typedef名称:

typedef struct Foo Foo;

typedef struct
{
int x;
}
Bar;

void foo (Foo *);
void bar (Bar *);

struct Foo
{
int y;
};

您无法预先声明 typedef,因此我们仍然需要一个可以转发的真正的 struct 类型。这里有一个小不一致之处:Foostruct Foo 相同,但没有 struct Bar,只有 Bar >。您可以通过切换到来解决这个问题

typedef struct Bar
{
int x;
}
Bar;

这同时定义了struct BarBar

关于c - 在 C 中是否可以一致地引用前向声明和非前向声明的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41531870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com