![](/img/trans.png)
[英]C++ Parent Class Default Constructor Called Instead of Parameterized Constructor
[英]C++: No default constructor exists for parent class
我正在为二叉搜索树 (BST) 编写 class 文件,它从 class (Tree) 扩展而来。 但是,我在当前文件 ( bst.cpp
) 的 IDE 中收到以下错误
class“树”不存在默认构造函数
在编译中,我收到以下错误:
没有匹配的 function 调用 'Tree::Tree()'
这看起来很奇怪,考虑到我已经在 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)
{
}
下面是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);
};
最后,下面是我的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)
{
}
你明白了, Tree
没有默认构造函数。 因此,您不能默认构造BST
,因为其中的Tree
将不知道如何构造自己。
您必须对其进行成员初始化。
BST::BST() : Tree(1) {}
你确定你不想将该值传递给BST
的构造函数吗?
BST::BST(int w) : Tree(w) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.