c++ - 图层树,没有合适的默认构造函数可用

标签 c++

我正在尝试实现一个 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并且只声明构造函数。然后你定义构造函数aftertree被完全定义,因为在构造函数中你需要tree的大小因为 subTree = new tree; 语句。但是你现在没问题了,因为类 tree 是完全可用的,并且可以毫无问题地定义构造函数。希望这是有道理的。

相关:When can I use a forward declaration?

关于c++ - 图层树,没有合适的默认构造函数可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30587796/

相关文章:

具有不同模板参数值的模板结构的 C++ 访问 protected 成员

c++ - 为什么需要在多个地方声明一个函数?

c++ - 范围解析和 this 运算符

C++ 调试错误

c++ - C++ 是否有办法忽略函数的异常?

c++ - 为什么win32线程不自动退出?

c++ - main() 之前的堆栈溢出异常

c++ - 在 C++ 中使用模板化方法交替传递仿函数和函数指针

c++ - GLUT 鼠标位置未更新

c++ - Constexpr 替代 placement new 能够使内存中的对象保持未初始化状态?