我创建了一个node.h类,定义了一个名为node的类,用于表示二叉树(任何类型)。似乎构造函数不起作用。错误在下面。我只是开始在类这样的类中编写构造函数,这是我第一次遇到二叉树。任何人都可以指出我正确的方向如何解决这些错误并使我的代码工作?谢谢。
Node.h
#ifndef NODE_H
#define NODE_H
#include <iostream>
//an object of type node holds 3 things
// - an item (oftype t)
// - a left subtree
// - a right subtree
template<typename T>
class Node {
public:
Node(T item); //constructor to create a leaf node
Node(T item, Node *lft, Node *rht); //constructor which creates an internal node
~Node(); //Destructor
//public data member functions:
bool searchTree(T key);
void printTree();
private:
//private data member functions:
//..
};
//constructor
template<typename T>
Node<T>::Node(T i, Node<T> *l, Node<T> *r) {
item = i;
lft = NULL;
rht = NULL;
}
//constructor //is this correct?
template <typename T>
Node<T>::Node(T i) { //should i be a parameter here?
item = i; //is this right?
}
//destructor
template <typename T>
Node<T>::~Node() {
delete left;
delete right;
//delete;
}
//print tree method
template <typename T>
void Node<T>::printTree() {
if (lft != NULL) {
lft->printTree();
cout << item << endl;//alphabetical order
}
if (rht != NULL) {
rht->printTree();
//cout << item << endl; //post order
}
}
//search Tree method
template <typename T>
bool Node<T>::searchTree(T key) {
bool found = false;
if (item == key) {
return true;
}
if (left != NULL) {
found = left->searchTree(key);
if (found) return true;
}
if (right != NULL) {
return right->searchTree(key);
}
return false; //if left and right are both null & key is not the search item, then not found == not in the tree.
}
#endif
Main.cpp的
#include "Node.h"
#include <iostream>
using namespace std;
//set up tree method
Node<string> *setUpTree() {
Node<string> *s_tree =
new Node<string>("Sunday",
new Node<string>("monday",
new Node<string>("Friday"),
new Node<string>("Saturday")),
new Node<string>("Tuesday",
new Node<string>("Thursday"),
new Node<string>("Wednesday")));
}
int main() {
Node<string> *s_tree;
s_tree = setUpTree();
cout << "Part 2 :Priting tree vals " << endl << endl;
s_tree->printTree();
cout << endl;
//search for range of tree values
//searchTree(s_tree, "Sunday");
//searchTree(s_tree, "Monday");
return 0;
}
答案 0 :(得分:1)
您在构造函数和其他方法中使用的成员没有声明。编译器不知道rht
或right
的含义。从你的代码来看,这个类看起来应该更像这样:
template<typename T>
class Node {
public:
Node(T item); //constructor to create a leaf node
Node(T item, Node *lft, Node *rht); //constructor which creates an internal node
~Node(); //Destructor
//public data member functions:
bool searchTree(T key);
void printTree();
private:
Node* left;
Node* right;
T item;
//private data member functions:
//..
};
现在编译器知道left
,right
和item
是什么意思。现在,您可以在该类的成员函数中使用这些标识符。请注意,编译器仍然不知道rht
或lft
是什么,因此您应该将其替换为right
和left
。
希望这有帮助