【发布时间】:2020-04-05 01:01:12
【问题描述】:
我将包含一个指向这个非常相似的问题的链接:C++ initial value of reference to non-const must be an lvalue 错误是一样的(引用非常量的初始值必须是左值)但情况不同。与该示例相反,在我的函数中,指针确实需要修改。我正在编写一个递归函数来将一个节点添加到二叉搜索树。该函数包含在此处。
1 void BST::insert(BSTNode*& current, BSTNode*& newNode)
2 {
3 //If empty, assign
4 if (current == nullptr)
5 current = newNode;
6
7 //If less, go left
8 else if (newNode->getEng() <= current->getEng())
9 insert(current->getLeft(), newNode);
10
11 //If greater, go right
12 else
13 insert(current->getRight(), newNode);
14 }
我在第 9 行和第 13 行得到错误。如图所示,我通过引用传递了 current 和 newNode 指针,但 newNode 没有问题,只有我的 current->getLeft() 和 current->getRight() 语句。在我链接到的问题中,评论说错误是因为只有在函数中修改值时才应该使用按引用传递。在current == nullptr 的第一种情况下,值被修改了,所以我不确定该怎么做。
编辑以包含 BSTNode 类
class BSTNode
{
public:
BSTNode();
BSTNode(char, string);
void setLeft(BSTNode* newLeft) { left = newLeft; }
void setRight(BSTNode* newRight) { right = newRight; }
BSTNode* getLeft() { return left; }
BSTNode* getRight() { return right; }
char getEng() { return Eng; }
string getMorse() { return Morse; }
private:
char Eng;
string Morse;
BSTNode* left;
BSTNode* right;
};
这是我的 BST 课程:
class BST
{
public:
BST(string fileName);
~BST();
bool isEmpty();
void addNode(char english, string morse);
void insert(BSTNode** current, BSTNode*& newNode);
//bool searchTree(char english, string& morse);
private:
BSTNode* root;
int nodeCount;
};
【问题讨论】:
标签: c++ binary-tree binary-search-tree