Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

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

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...