通过引用传递指针时出错

问题描述 投票:1回答:1

我将提供指向这个非常相似的问题的链接:C++ initial value of reference to non-const must be an lvalue错误是相同的(对非const的引用的初始值必须是一个左值),但情况有所不同。与该示例相反,在我的函数中,确实需要修改指针。我正在编写一个递归函数,将一个节点添加到二进制搜索树中。该功能包含在此处。

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行出现错误。如图所示,我同时通过引用传递了当前指针和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
1个回答
0
投票

编译器使您免于破损。在第9行插入的调用中,您正在向insert传递对current->getLeft()返回的临时文件的引用。如果您随后修改该临时文件,修改将丢失。修复getLeft以返回可修改的引用。

© www.soinside.com 2019 - 2024. All rights reserved.