我正在尝试实现一个 RB 树,在我的树中,每个节点还有一个指向另一个 RB 树的指针。我的代码如下所示:
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
的构造函数将再次出现同样的问题。我应该怎么办?
最佳答案
前向声明类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
};
最后在类外定义节点
的构造函数,但是在类树
的完整定义之后,
class tree
{
// implementation
};
node::node()
{
subTree = new tree; // no more error here !!
}
Live example on Coliru
这里的技巧是,只要您将它们用作指针/引用并且不需要计算/使用它们的大小,类就可以包含不完整的类型(即只有声明可用但没有完整定义的类型)。因此,您可以在 node
类之前转发声明 tree
,然后在您的类 node
中声明指针 tree* subtree
并且只声明构造函数。然后你定义构造函数after类tree
被完全定义,因为在构造函数中你需要tree
的大小因为 subTree = new tree;
语句。但是你现在没问题了,因为类 tree
是完全可用的,并且可以毫无问题地定义构造函数。希望这是有道理的。
关于c++ - 图层树,没有合适的默认构造函数可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30587796/