我正在尝试为二进制搜索树编写一个简单的类,该类使用使用模板的节点类。这是我的代码:
当我尝试编译代码时,出现此错误:
'Node<T>': no appropriate default constructor available'
为此行:
Tree() : root(0), counter(0) {}
而且我不明白为什么这里甚至要使用默认构造函数,我只是给类类型的指针赋值。
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Node {
public:
Node(const T &value) : value(value), Left(0), Right(0) {}
~Node() {
if (Left != 0)
delete Left;
if (Right != 0)
delete Right;
}
Node& getLeft() { return *Left; }
Node& getRight() { return *Right; }
private:
Node* Left;
Node* Right;
T value;
};
template <typename T>
class Tree : public Node<T> {
public:
template<typename T>
friend ostream& operator<<(ostream& output, const Tree<T> &t);
Tree() : root(0), counter(0) {}
Tree(const T &rootValue) : root(new Node<T>(rootValue)), counter(1) {}
~Tree() { delete root; }
Tree& insert(const T &value) {
Node<T> *runner = root;
Node<T> *replacer = root;
if (runner == 0)
root = new Node<T>(value);
else
{
while (runner != 0)
{
replacer = runner;
if (value > runner->value)
runner = runner->Right;
else
runner = runner->Left;
}
if (value > replacer->value)
replacer->Right = new Node<T>(value);
else
replacer->Left = new Node<T>(value);
}
counter++;
return *this;
}
bool exists(const T &value) const {
Node<T> *runner = root;
while (runner != 0)
{
if (value == runner->value)
return true;
if (value > runner->value)
runner = runner->Right;
else
runner = runner->Left;
}
return false;
}
int size() const { return size; }
private:
Node<T> *root;
int counter;
};
template<typename T>
string preorderToString(const Node<T> &n) { //Function that receives a tree and returns a string of the preorder traversal of it
string left, middle, right;
if (n.Left != 0)
left = preorderToString((*n.Left)) + " ";
middle = to_string(n.value);
if (n.Right != 0)
right = " " + preorderToString((*n.Right));
return left + middle + right;
}
template<typename T>
ostream& operator<<(ostream& output, const Tree<T> &t) //Operator overloading that uses the function 'preorderToString' to print the tree contents
{
return output << preorderToString<T>(*(t.root));
}
int main() {
Tree<double> test;
}
答案 0 :(得分:0)
该消息有点误导性:它不是在抱怨您已初始化的成员,而是您未初始化的基础。因此,它正在尝试使用不存在的基(Node<double>
)的默认构造函数。
也许您不是故意要使Tree<T>
源自Node<T>
吗?
修复该问题(以及该好友声明上阴影的T
)the code compiles。