class Node {
private:
Node *left = NULL, *right = NULL;
char data;
public:
Node(char new_data) {
data = new_data;
}
Node *get_left() {
return left;
}
Node *get_right() {
return right;
}
char get_data() {
return data;
}
void set_data(char new_data) {
data = new_data;
}
};
我已经调试过了(使用gdb和cout),似乎set_data函数就是问题所在。为什么呢?
还有更多代码,但我假设没有必要使用更多代码。
编辑:
class tree {
private:
Node *root;
public:
tree(char ch) {
cout << "ASDASD"; //using this to identify error
root->set_data(ch);
cout << root->get_data(); //using this to identify error
}
};
编辑2:
#include <iostream>
#include "tree.h"
#include <cctype>
using namespace std;
int main () {
char c;
cout << "Enter a series of letters: ";
cin >> c;
tree t(c); //sets first one to root
while(cin) { //change??
cin >> c;
if (isdigit(c)) break;
Node *n;
n->set_data(c);
t.insert(n);
}
}
代码应该从键盘读取,直到读取数字。它会读取所有字母,但是当我键入一个数字以尝试退出时,会出现段错误。
答案 0 :(得分:1)
class tree {
private:
Node *root;
public:
tree(char ch) {
cout << "ASDASD"; //using this to identify error
root->set_data(ch); // **HERE**
cout << root->get_data(); //using this to identify error
}
};
此时,root
并未指出任何内容。所以试图取消引用它是一个错误。在使用指针指向的东西之前,必须使指针指向某个东西。
你在这里遇到同样的问题:
Node *n;
n->set_data(c);
set_data
函数用于设置Node
的数据。所以你必须已经有Node
来调用它。您没有在任何地方创建Node
,而n
并未指向此处。{/ p>