为什么不能一个结构是自身的成员? [英] Why can't a struct be a member of itself?
问题描述
我有一个结构富
。声明类型富*
的成员如下:
typedef结构美孚
{
结构* foo的孩子[26];
} foo的;
但是,如果我试图声明类型的成员富
我得到一个错误:
typedef结构美孚
{
结构foo的孩子[26];
} foo的;
本声明给我的错误
结构富'的定义是不完整的,直到结束的'}
块引用>解决方案一个结构
T
不能包含自身。你怎么知道它的大小?这将是不可能这样做的,因为T
的大小将要求您知道T
的大小(因为T
包含另一个T
)。这变成一个无限递归。您可以有一个指针
T
在结构内部T
因为一个指针的大小是不一样的尺寸为指向的对象:在这种情况下,你只储存的内存地址在另一个T
存储 - 所有你需要做的空间基本上是空间,你需要存储的内存地址在另一个T
生活。I have a struct
foo
. Declaring a member of typefoo*
works:typedef struct foo { struct foo* children[26]; } foo;
But if I try to declare a member of type
foo
I get an error:typedef struct foo { struct foo children[26]; } foo;
This declaration gives me the error
definition of 'struct foo' is not complete until the closing '}'
解决方案A structure
T
cannot contain itself. How would you know its size? It would be impossible to do so, because the size ofT
would require you to know the size ofT
(becauseT
contains anotherT
). This turns into an infinite recursion.You can have a pointer to
T
inside a structureT
because the size of a pointer is not the same size as the pointed-to object: in this case, you would just store an address of memory where anotherT
is stored - all the space you need to do that is basically the space you need to store a memory address where anotherT
lives.这篇关于为什么不能一个结构是自身的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!