【问题标题】:Cannot take address of rvalue error in a recursive function for a binary tree无法在二叉树的递归函数中获取右值错误的地址
【发布时间】:2016-11-17 22:44:59
【问题描述】:

我正在尝试为我的二叉搜索树创建一个递归插入函数。但是,我不断收到以下错误“无法获取 Node* 类型的右值的地址”。我知道如果我的指针为 NULL,那么获取它的地址会给我这个错误,但是我将如何解决这个问题呢?

注意:Node(data* _data) 构造函数在创建对象时将左右指针设置为 NULL。

这是我的代码,我已经注释了产生右值错误的两行。我也在使用 Xcode。

提前致谢。

class Node {
private:
data* data;
Node* left;
Node* right;

public:
Node(data* _data);

~Node();

Node* getLeft(); // gets the left immediate descendent of the Node.

Node* getRight(); // gets the right immediate descendent of the Node

data* getVal(); //returns pointer to data
};


class Tree {

private:
Node* root;
int nodeCount;
Node* placeNode(Node** root, data* data);

public:
Tree();

~Tree();

bool placeIn(data* newData); //placeIns node into ordered BST
};


bool Tree::placeIn(data* newData) {

return placeNode(root, newData); //placeIns newData object into BST
}


Node* Tree::placeNode(Node** root, data* data) {
//placeIns node into BST via in order traversal


if ((*root) == NULL) {
    return (*root) = new Node(data);
}


if ((*root)->getVal()->getName() == data->getName()) {
    cout << "Node exists" << endl;
    return NULL;
}

if ((*root)->getVal()->getName() > data->getName()) {
    placeNode(&(*root)->getLeft(), data); //Cannot take the address of an rvalue of type Node*
}

else {
    placeNode(&(*root)->getRight(), data); //Cannot take the address of an rvalue of type Node*
}

return NULL;
}

【问题讨论】:

  • 您的代码无法编译(由于与问题无关的问题)并且您没有说出错误是什么,因此很难提供帮助。 godbolt.org/g/RZFQXK
  • “右值错误”的描述性不是很好。
  • 代码只是我的程序的简化版本。我已经编辑了上面的内容,现在准确地说明了错误。

标签: c++11 pointers object xcode7 binary-search-tree


【解决方案1】:

getLeft()getRight() 返回右值,这意味着它们返回一个临时对象,该对象是其他对象的副本。不能取临时地址。

如果您可以获取这些临时对象的地址,placeNode 函数不会做任何有用的事情,因为它会将临时对象设置为 new Node(data) 表达式的结果,然后临时会消失,泄漏您刚刚创建的新节点的内存。错误是通过拒绝编译损坏的代码来帮您一个忙。

如果您打算将成员变量leftright 设置为新节点,那么您需要这样做,而不是设置这些变量的一些临时副本。为此,您需要使 getLeftgetRight 返回指向成员变量的引用或指针,而不是它们的副本。要么返回成员变量的地址(而不是获取临时副本的地址),或者为了更惯用的 C++ 返回对成员变量的引用并将 placeNode 更改为采用 Node*&amp; 而不是 Node*。或者提供setLeft()setRight() 成员函数,保持getter 不变。

但代码中还有其他错误,例如return root = new Node(data) 不会编译,因为 rootNode** 而不是 Node*(您是要取消引用它吗?如果您将其设为 Node*&amp;,那么您就不需要了。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    相关资源
    最近更新 更多