我正在尝试使用新值更新节点,但是当我在另一个函数中打印出节点时,将显示旧值。我也试过设置问题'到updateTree()的返回值,它将返回新的更新节点,但产生相同的结果。
void f(Node *n){//n is a pointer that has a string value with a left and right pointer. lets say that "n" right now is "duck"
//do stuff....
updateTree(n);
cout << n->value;//prints out "duck" rather than the updated value..
}
void updateTree(Node *question){
string animal, q;
cout << "Darn, I lost. What was is? ";
getline(cin, animal);
cout << "Enter a question that is true for a(n) " << animal << " and false for a(n) " << question->value << ": ";
getline(cin, q);
Node right(question->value, nullptr, nullptr);//the old animal ie "duck"
Node left(animal, nullptr, nullptr);//the new animal
question = new Node(q, &left, &right);//updated "n" ie "duck" to something else
}
答案 0 :(得分:1)
您的代码
void updateTree(Node *question) {
// ^^^^^^ That's a copy of the pointer variable passed.
// Assignments will never affect the original pointer value
// ...
question = new Node(q, &left, &right);
}
将新创建的Node
发送到void,它会在函数离开作用域时丢失。您正在对该指针变量的副本进行操作。
您实际需要的是 参考 ,它允许更改原始指针:
void updateTree(Node*& question) {
// ^