【问题标题】:Error when passing a pointer by reference通过引用传递指针时出错
【发布时间】: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-&gt;getLeft()current-&gt;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】:

    编译器让您免于损坏。在第 9 行的 insert 调用中,您将向 insert 传递对 current-&gt;getLeft() 返回的临时对象的引用。如果您随后修改该临时文件,则修改将丢失。修复 getLeft 以返回可修改的引用。

    【讨论】:

      猜你喜欢
      • 2014-07-27
      • 2023-03-03
      • 1970-01-01
      • 2012-07-06
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多