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

2019-01-02 15:35发布

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

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

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 left or right as Node types.

标签: c++
4条回答
姐姐魅力值爆表
2楼-- · 2019-01-02 16:09

You should use a pointer, & better initialized:

class Node {
    char * cargo = nullptr;
    Node * left = nullptr;
    Node * right = nullptr;
};
查看更多
妖精总统
3楼-- · 2019-01-02 16:13

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

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
};
查看更多
裙下三千臣
4楼-- · 2019-01-02 16:24

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

class Node
{
    Node *pnode;
    Node &rnode;
};
查看更多
高级女魔头
5楼-- · 2019-01-02 16:25

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.

查看更多
登录 后发表回答