在C++中的结构定义中使用结构本身

Using the struct itself in the definition of struct in C++

本文关键字:结构 定义 C++      更新时间:2023-10-16

我想在C++中实现一个简单的树结构,比如:

struct node{
    ....
    node* parent;
    node[]* children;
    ....
};

但是编译器报告了一个错误(CLang++和G++)

error: expected unqualified-id before '[' token
node[]* child;
    ^
error: expected ',' or '...' before '*' token
node(node[]* c): : child = c; {}
           ^

像这个

顺便说一句,我正在为一些c++11功能使用-std=c++11标志

任何帮助都会通知

结构的大小是编译时常数。如果您给出一个size to be determined later的数组,则这是一个错误。给定一定的大小(对于二进制树的情况下的ex 2)或使用pointer to node *存储数组或指针(子级),或使用一些内置容器(对于ex std::vector,std::array)

node[]* children;不是合法的C++语法。如果最大在编译时,子级的数量是已知的,您可以写:

node* children[maxChildren];

否则:

std::vector<node*> children;

会成功的。如果maxChildren较大或可变,则可能还是要使用此表单。另一方面,如果maxChildren是2,您可能只需要声明两个指针:

node* leftChild;
node* rightChild;