我正在尝试实现RB-Tree,在我的树中每个节点都有一个指向另一个RB-Tree的指针。我的代码如下所示:
class node{
tree* subTree;
. . . //some code goes here
node(){
subTree = new tree; //error here !!
}
};
class tree{
. . . //some code
};
问题是,由于node
是在tree
之前定义的,编译器会给我No appropriate default constructor available
。如果我在树类之后移动节点类,那么node
的构造函数会再次发生同样的问题。我该怎么办?
答案 0 :(得分:2)
转发声明类tree
,然后只使用类node
中的构造函数声明,
class tree; // forward declaration, allows node to contain incomplete tree types
class node
{
tree* subTree;
public:
//some code goes here
node(); // only the declaration
};
最后定义了类外node
的构造函数,但 类tree
的完整定义,
class tree
{
// implementation
};
node::node()
{
subTree = new tree; // no more error here !!
}
Live example on Coliru
这里的技巧是,只要您将它们用作指针/引用并且不需要计算/使用它们的大小,类就可以包含不完整类型(即只有声明可用但不是完整定义的类型)。因此,您可以在课程tree
之前转发声明node
,然后在您的班级tree* subtree
中声明指针node
,并且仅声明构造函数。然后在完全定义类tree
之后定义 构造函数,因为在构造函数中,由于{{1},您需要tree
的大小声明。但是你现在没问题,因为类subTree = new tree;
完全可用,并且可以毫无问题地定义构造函数。希望这是有道理的。