gpt4 book ai didi

c++ - BST 插入 "expression must be modifiable lvalue"C++

转载 作者:行者123 更新时间:2023-11-28 06:43:14 24 4
gpt4 key购买 nike

我正在学习 BST,但遇到了这个错误。我最初将 Node 作为一个结构,当我直接访问左/右成员时它工作正常。我正在尝试使 Node 成为一个类并改用访问器函数。

编辑:我正在使用一个接口(interface),因此 getLeftChild()getRightChild() 的返回类型不能更改。

节点的实现:

    #include "Node.h"
#include <iostream>

Node::Node(int dataP)
{
data = dataP;
left = NULL;
right = NULL;
}

Node::~Node()
{
}

int Node::getData()
{
return data;
}

NodeInterface* Node::getLeftChild()
{
return left;
}

NodeInterface* Node::getRightChild()
{
return right;
}

当我尝试将 address->getLeftChild() 分配给新节点时出现此错误(见标题)。

我的部分添加功能:

if (data < address->getData())
{
if (address->getLeftChild() == NULL)
{
address->getLeftChild() = new Node(data);
return true;
}
else
{ //Something is there
return rAdd(address->getLeftChild(), data);

}

谢谢!

最佳答案

getLeftChild 返回节点指针的拷贝。分配给它不会做任何有用的事情。

如果你想允许通过该函数分配给节点的指针,返回一个引用:

Node*& getLeftChild()

提供 setLeftChild 或简单地将指针公开为公共(public)成员可能更清楚(因为无论如何您都没有提供任何封装)。或者,如果这发生在可以访问私有(private)成员的成员函数中,请将其作为 address->left 访问。

关于c++ - BST 插入 "expression must be modifiable lvalue"C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25531711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com