c++ 类可以将自身作为成员包含吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2706129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:25:33  来源:igfitidea点击:

Can a c++ class include itself as an member?

c++

提问by Peter Stewart

I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.

我试图通过用 C++ 编写 Python 例程来加速它,然后使用 ctypes 或 cython 使用它。

I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.

我是 C++ 的新手。我使用的是免费的 Microsoft Visual C++ Express。

I plan to implement an expression tree, and a method to evaluate it in postfix order.

我计划实现一个表达式树,以及一种按后缀顺序计算它的方法。

The problem I run into right away is:

我马上遇到的问题是:

class Node {
    char *cargo;
    Node left;
    Node right;
};

I can't declare leftor rightas Nodetypes.

我不能声明leftright作为Node类型。

回答by James McNellis

No, because the object would be infinitely large (because every Nodehas as members two other Nodeobjects, which each have as members two other Nodeobjects, which each... well, you get the point).

没有,因为对象将是无限大(因为每一个Node有作为成员另外两个Node对象,每个有作为成员另外两个Node对象,每......好吧,你明白了吧)。

You can, however, have a pointer to the class type as a member variable:

但是,您可以将指向类类型的指针作为成员变量:

class Node {
    char *cargo;
    Node* left;   // I'm not a Node; I'm just a pointer to a Node
    Node* right;  // Same here
};

回答by Felipe

Just for completeness, note that a class can contain a static instance of itself:

为了完整起见,请注意一个类可以包含自身的静态实例:

class A
{
    static A a;
};

This is because static members are not actually stored in the class instances, so there is no recursion.

这是因为静态成员实际上并未存储在类实例中,因此没有递归。

回答by R Samuel Klatchko

No, but it can have a reference or a pointer to itself:

不,但它可以有一个引用或指向它自己的指针:

class Node
{
    Node *pnode;
    Node &rnode;
};

回答by Amit G.

You should use a pointer, & better initialized:

您应该使用指针,并更好地初始化:

class Node {
    char * cargo = nullptr;
    Node * left = nullptr;
    Node * right = nullptr;
};