【问题标题】:initial value of reference to non-const must be an lvalue when calling a function调用函数时非常量引用的初始值必须是左值
【发布时间】:2017-04-13 12:38:30
【问题描述】:

我识别出这样的二叉树:

class Btree
{
public:
    BtreeNode <T>* root;
    ...
}

然后我在二叉树类中写了一个插入函数,如下所示:

void Btree<T>::InsertNode2(T data, BtreeNode <T>* &root)
{
    if (root==NULL)
    {
        root = new BtreeNode <T> (data);
        //cout << root->data << endl;
        return ;
    }
    if (data <= root->data)
        InsertNode2(data, root->leftchild);
    else
        InsertNode2(data, root->rightchild);
}

当我调用这个函数时:

Btree<int> *tree=new Btree<int>();
tree->InsertNode2(1, tree->root);

没关系。一切正常。

但是如果我写另一个函数来获取root:

BtreeNode <T>* GetRoot(){ return this->root; }

当我调用 InsertNode2 时:

Btree<int> *tree=new Btree<int>();
tree->InsertNode2(1, tree->GetRoot());

有一个错误:非常量引用的初始值必须是左值。 这两种方法有什么区别?如何修改它?我希望 root 是私有的。

【问题讨论】:

  • 区别在于tree-&gt;root是成员变量,而tree-&gt;GetRoot()是该成员变量的副本。

标签: c++ pointers binary-tree


【解决方案1】:

按值而不是按引用获取 BtreeNode 指针。例如

void Btree<T>::InsertNode2(T data, BtreeNode <T>* root)

这应该可以解决您的问题。

【讨论】:

【解决方案2】:

您的InsertNode2 函数是您的树的私有详细信息。您的树应该有一个公共插入接口,如下所示:

class Btree
{
    BtreeNode <T>* root;

public:
    void Insert(const T& data) { InsertNode2(data, root); }

    // ...
};

树根当然也应该是你的树的私有细节。

您的GetRoot 函数返回根指针的副本,当然尝试修改副本是没有意义的。您甚至可能拥有 GetRoot 函数,因为见上文。

【讨论】:

  • InsertNode2 函数也是公开的。二叉树类中的所有内容都是公开的,但错误仍然存​​在。
  • @user7857293:注意细节。我没有说InsertNode2“有private 访问权限”,我说它“是一个私人细节”。我说的是设计,而不是代码细节。设计产生的代码细节是函数应该只有private访问,但这是次要问题。在实施之前先了解设计。
  • 我得想一想-_-!。谢谢你的回答。
猜你喜欢
  • 2013-07-20
  • 1970-01-01
  • 2022-11-30
  • 2019-06-14
  • 1970-01-01
  • 2021-06-15
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多