【问题标题】:error: use of deleted function while implementing BST错误:在实现 BST 时使用已删除的函数
【发布时间】:2020-05-18 18:34:00
【问题描述】:

我正在尝试实现一个简单的二叉搜索树,但我遇到了一些问题,我无法弄清楚这里有什么问题。

#include<bits/stdc++.h>
using namespace std;

class Node{
public:
    int data;
    Node* left = NULL;
    Node* right = NULL;

    Node(int x):data(x)
    {}
};

//BST Extends the Node class
class BST : public Node{
public:
    Node* root = NULL;
    //basic operations
    void insertion(Node* root, int x);
    void preorder(Node* root);
};

void BST::insertion(Node* root, int x) {
    Node* newNode = new Node(x);
    if(!root) {
    root = newNode;
    return;
    }
    if(x > root->data) BST::insertion(root->right, x);
    if(x < root->data) BST::insertion(root->left, x);
}

void BST::preorder(Node* root) {
    if(!root) return;

    cout << root->data << " ";
    BST::preorder(root->left);
    BST::preorder(root->right);
}

int main() {
    BST tree;
    tree.insertion(tree.root, 8);
    tree.insertion(tree.root, 6);
    tree.insertion(tree.root, 12);
    tree.insertion(tree.root, 10);
    tree.preorder(tree.root);
    return 0;
   }

这些是错误:

BST.cpp:46:6: error: use of deleted function 'BST::BST()'
BST tree;
      ^~~~
BST.cpp:17:7: note: 'BST::BST()' is implicitly deleted because the default definition would be ill-formed:
 class BST : public Node{
       ^~~
BST.cpp:17:7: error: no matching function for call to 'Node::Node()'
BST.cpp:12:2: note: candidate: 'Node::Node(int)'
  Node(int x):data(x)
  ^~~~
BST.cpp:12:2: note:   candidate expects 1 argument, 0 provided
BST.cpp:6:7: note: candidate: 'constexpr Node::Node(const Node&)'
 class Node{
       ^~~~
BST.cpp:6:7: note:   candidate expects 1 argument, 0 provided
BST.cpp:6:7: note: candidate: 'constexpr Node::Node(Node&&)'
BST.cpp:6:7: note:   candidate expects 1 argument, 0 provided

我检查了几个答案,但无法找出导致问题的原因,我认为这是构造函数和数据成员的问题

【问题讨论】:

标签: c++ c++11 c++14 binary-search-tree


【解决方案1】:

你没有给你的根节点一个值。

BSTNodeNode 的唯一构造函数需要 int val。没有默认构造函数——它已被禁止,或者用 C++ 术语来说,是“删除”。

您需要给BST 一个类似的构造函数以将其传递给Node(或编写using Node::Node 以继承它),并且您在main 中的tree 声明需要提供一个值。

【讨论】:

  • 对不起,我无法理解你的意思是BST一个类似的构造函数,请澄清
  • 它需要一个BST(int x) : Node(int x) .. 不过,仔细观察,我不相信你想让BST成为一个Node,因为它包含它的根节点。也许只是删除继承?
猜你喜欢
  • 2015-02-03
  • 2015-10-25
  • 1970-01-01
  • 2022-01-07
  • 2014-04-16
  • 1970-01-01
  • 2020-09-10
  • 2019-03-03
  • 1970-01-01
相关资源
最近更新 更多