两个结构的顺序
我有这两种结构...
typedef struct{
MY_SECOND_STRUCT s1;
}MY_FIRST_STRUCT;
typedef struct{
int s1;
}MY_SECOND_STRUCT;
我更喜欢这个顺序,我不想切换它们。 但编译器目前不知道 MY_SECOND_STRUCT 并且出现错误
错误:“MY_SECOND_STRUCT”之前应有说明符限定符列表
我尝试将声明添加到顶部
struct MY_SECOND_STRUCT;
并将定义更改为
typedef struct{
struct MY_SECOND_STRUCT s1;
}MY_FIRST_STRUCT;
但没有帮助。
I have these two structures...
typedef struct{
MY_SECOND_STRUCT s1;
}MY_FIRST_STRUCT;
typedef struct{
int s1;
}MY_SECOND_STRUCT;
I prefer this order, I dont want to switch them.
But compiler dont know MY_SECOND_STRUCT at the moment and I get error
error: expected specifier-qualifier-list before 'MY_SECOND_STRUCT'
I´ve tried add declaration to the top
struct MY_SECOND_STRUCT;
also change definition to
typedef struct{
struct MY_SECOND_STRUCT s1;
}MY_FIRST_STRUCT;
but it didnt help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你必须切换它们。
如果
MY_FIRST_STRUCT
具有MY_SECOND_STRUCT
类型的成员变量,则MY_SECOND_STRUCT
必须在定义之前定义且完整(而不仅仅是声明和不完整) >MY_FIRST_STRUCT
。You have to switch them.
If
MY_FIRST_STRUCT
has a member variable of typeMY_SECOND_STRUCT
thenMY_SECOND_STRUCT
must be defined and complete (not just declared and incomplete) before the definition ofMY_FIRST_STRUCT
.该命令是不可能的。你必须切换它们。
但是,如果您将成员声明为指针,则不需要切换:
或者,在 C++ 中,您可以将模板用作:
当您想使用 MY_FIRST_STRUCT 时,只需使用此 typedef 即可code>:
立即使用
MY_FIRST_STRUCT
。 :-)That order is not possible. You have to switch them.
However, if you declare the member as pointer, then switching is not required:
Or, in C++ you can use template as:
And when you want to use
MY_FIRST_STRUCT
, just use thistypedef
:Use
MY_FIRST_STRUCT
now. :-)当您创建第一个结构时,编译器尚未遇到第二个结构。它需要知道
MY_SECOND_STRUCT
位是多少,因为那时它需要决定MY_FISRT_STRUCT
的大小以及如何为其分配内存。简单地向前声明 structMY_FIRST_STRUCT
是不够的,这不会告诉编译器该结构的大小或内容。如果您使用指向结构的指针,则前向声明会起作用,但在尝试包含实际结构时,前向声明还不够。您唯一真正的选择是将
MY_SECOND_STRUCT
移至MY_FIRST_STRUCT
上方,或者使MY_FIRST_STRUCT
采用指针。乍一看,这可能看起来很奇怪,但对此我们无能为力。At the time you cerate your first struct the compiler hasn't come across the second struct yet. It needs to know how bit
MY_SECOND_STRUCT
is because at that time it needs to decide how big to makeMY_FISRT_STRUCT
and how to lay out the memory for it. Simply forward declaring structMY_FIRST_STRUCT
is not enough, that doesn't tell the compiler about the size or contents of the struct. Forward declaring would work if you were using a pointer to a struct, but it's not enough when trying to include the actual structure.Your only real options are to move
MY_SECOND_STRUCT
up aboveMY_FIRST_STRUCT
or to makeMY_FIRST_STRUCT
takes a pointer. It might seem strange at first, but there's not much that can be done about it.