简体   繁体   English

C++:父 class 不存在默认构造函数

[英]C++: No default constructor exists for parent class

I am writing the class file for a binary search tree (BST), which extends from the class (Tree).我正在为二叉搜索树 (BST) 编写 class 文件,它从 class (Tree) 扩展而来。 However, I receive the following error in my IDE for the current file ( bst.cpp )但是,我在当前文件 ( bst.cpp ) 的 IDE 中收到以下错误

在此处输入图像描述 stating:说明:

no default constructor exists for class "Tree" class“树”不存在默认构造函数

In compilation, I receive the following error:在编译中,我收到以下错误:

no matching function for call to 'Tree::Tree()'没有匹配的 function 调用 'Tree::Tree()'

This seems strange, considering that I have already defined a default constructor in my Tree class implementation and have imported the class into my bst.cpp file:这看起来很奇怪,考虑到我已经在 Tree class 实现中定义了一个默认构造函数,并将 class 导入到我的bst.cpp文件中:

// Import dependencies
#include "datastructure.hpp"
#include "tree.cpp"

// Import libraries
#include <fstream>
#include <sstream>

using namespace std;

BST::BST() {
    
}

void BST::solution(const char *input_path, const char *output_path)
{
}

Below is datastructure.hpp :下面是datastructure.hpp

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

typedef struct TreeNode { 
   int key;
   int val;
   bool flag;
   int num_children;
   TreeNode **children;
} TreeNode; 

class Tree {
    protected:
        TreeNode* root;
        int max_width;
    public:
        Tree(int width);
        static void solution(const char *input_path, const char *output_path);

};

class BST: public Tree {
    protected:
        int max_width = 2;
        
    public:
        BST();
        static void solution(const char *input_path, const char *output_path);
};

And finally, below is my tree.cpp :最后,下面是我的tree.cpp

#include "datastructure.hpp"

#include <fstream>
#include <sstream>
#include <queue> 

using namespace std;

Tree::Tree(int width) {
    max_width = width;
}

void Tree::solution(const char *input_path, const char *output_path)
{
}

You got it there, Tree does not have a default constructor.你明白了, Tree没有默认构造函数。 As a result of that, you cannot default-construct a BST , because the Tree that is inside it will not know how to construct itself.因此,您不能默认构造BST ,因为其中的Tree将不知道如何构造自己。

You have to member-initialize it.您必须对其进行成员初始化。

BST::BST() : Tree(1) {}

Are you sure you don't want to pass that value to the constructor of BST though?你确定你不想将该值传递给BST的构造函数吗?

BST::BST(int w) : Tree(w) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM