为什么不能一个结构是自身的成员? [英] Why can't a struct be a member of itself?

查看:71
本文介绍了为什么不能一个结构是自身的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构。声明类型富* 的成员如下:

  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 type foo* 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 of T would require you to know the size of T (because T contains another T). This turns into an infinite recursion.

You can have a pointer to T inside a structure T 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 another T is stored - all the space you need to do that is basically the space you need to store a memory address where another T lives.

这篇关于为什么不能一个结构是自身的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆