自指结构声明 [英] Self referring structure declaration
问题描述
该follwing声明是有效的。
结构节点
{
int类型的;
结构节点*接下来的;
};
然而,当我们定义了下面,它给错误。
错误:场下一步具有不完整的类型
为什么会这样呢?
结构节点
{
int类型的;
结构节点旁边; / *不是指针* /
};
在结构节点节点
是一个结构标签,这在点你写它创建了一个不完全类型:一个结构变量,它是不是在宣告这一点,但没有定义。该类型是不完整之前的最后};
你的结构的
在C,一个不完全类型可即使是在它完全定义,使用指针该类型引用。然而,你不能分配类型的变量(实例),因为实际的结构定义尚未确定。 (它的工作原理完全一样的C ++抽象基类,如果你熟悉的。)
所以,当你写
结构节点{
int类型的;
结构节点*接下来的;
};
行结构节点*下一
表示这里是一个指向一个结构节点,尽管我不知道该类型是如何定义的呢。但是你不能声明类型的变量结构节点
这非常相同类型的结构定义里面,仅仅是因为你不能使用的东西你已经创建它。
The follwing declaration is valid.
struct node
{
int a;
struct node *next;
};
However, when we define the following, it gives error.
"error: field ‘next’ has incomplete type"
Why is it so?
struct node
{
int a;
struct node next; /* Not a pointer */
};
node in struct node
is a "struct tag", which at the point you write it creates an "incomplete type": a struct variable which is not at this point declared, but not defined. The type is not complete before the final };
of your struct.
In C, an incomplete type can be referenced even before it is fully defined, by using a pointer to that type. You can however not allocate a variable (instance) of that type, because the actual struct definition is yet to be defined. (It works exactly like abstract base classes in C++, if you are familiar with those.)
So when you write
struct node {
int a;
struct node *next;
};
the row struct node *next
means "here is a pointer to a struct node, even though I have no idea how that type is defined yet". But you cannot declare a variable of type struct node
inside the struct definition of that very same type, simply because you cannot use something before you have created it.
这篇关于自指结构声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!