在类本身中创建一个类的实例 [英] Create an instance of a class in the class itself

查看:129
本文介绍了在类本身中创建一个类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,并有一个问题:

I am new to C++ and have a question:

比较以下代码:

class Node { 
public:
    int data;
    Node* x;
};

class Node { 
public:
    int data;
    Node x;
};

我知道代码的第二部分不能通过编译。但我想知道原因。

I know the second part of code can't pass compile. But I want to know the reason.

它是与内存分配还是语法规范相关?

Is it related to memory allocation or just syntax regulation?

推荐答案

第二个片段中的代码无法编译,因为类 Node 在您声明其数据成员的地方未完全定义 x 节点 type。

The code in your second fragment cannot compile, because the class Node is not completely defined at the point where you declare its data member x of Node type.

为了理解起见,想象如果它可以编译,会导致某种无限递归结构内存量。
这是一个类对象的假想布局:

For the sake of understanding, imagine if it could compile, it would lead to some sort of "infinite recursion structure", that would take an infinite amount of memory. Here's the hypothetical layout of such a class object:

{
  data: int
  x: Node
  {
    data: int
    x: Node
    {
      data: int
      x: Node
      {
        ...
      }
    }
  }
}

第一种情况下工作,因为你不需要一个类完全定义为了声明一个指针。

我发现完全定义的思想是编译器知道这个类有多大有助于解决这样的问题:编译器需要知道一个类的大小是声明它的一个实例,但不是声明一个指向它的指针,它具有相同的大小,而不管类。

The first case works because you do not need a class to be fully defined in order to declare a pointer to it.
I find that thinking of "fully defined" as "the compiler knows how big this class is" helps to reason about problems like this: the compiler needs to know how big a class is to declare an instance of it, but not to declare a pointer to it, which has the same size regardless of the class.

这篇关于在类本身中创建一个类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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