c ++指针和指向引用的指针 [英] c++ pointers and pointer to a reference

查看:232
本文介绍了c ++指针和指向引用的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个二进制搜索树。我已经使用递归的过程将节点插入到树中。代码如下。

Im trying to create a Binary search tree. I've used recursive procedures to insert nodes into the tree. The code is as follows.

void BST :: insertRoot(Node* node, int data)    {
    if (node == NULL)
        this -> root = new Node(data);
    else
        insertOthers(node, data);
}
void BST :: insertOthers(Node* node, int data)  {
    if(node == NULL)    {
            node = new Node(data);
            return;
    }
    if(data < node->getData())
        insertOthers(node->getLeft(), data);
    else
        insertOthers(node->getRight(), data);
}

在此代码中,只有一个节点插入到树中,然后连接是破碎。但是,当我将 Node * 更改为 Node *& 时,它的工作原理很好。我仍然不明白这两者之间的区别。任何人都可以用他们的记忆映射来解释这两者之间的区别吗?谢谢

In this code only one node is inserted into the tree and then the connection is broken. However i when I change my Node* to Node*& it works perfectly. Still i cant understand whats the difference between these two. Can anyone explain the differentiation between these two with their memory mapping? Thank you

推荐答案

如果您通过值取指针参数:

If you take the pointer parameter by value:

Node* node

然后修改它:

node = new Node(data);

将更改函数内的局部变量;但不是来电者的观点。这个新值将会丢失,树将保持原样。

will change the local variable within the function; but not the caller's argument. This new value will be lost, and the tree will remain as it was.

传递引用(这是对指针的引用,而不是指向引用的指针):

Passing by reference (that's a reference to a pointer, not a pointer to a reference):

Node*& node

意味着本地参数指向与调用者参数相同的指针,因此调用者将看到改变为新价值。所以,假设逻辑的其余部分是正确的,这将更新树中的指针,以指向新的节点,如你所愿。

means that the local parameter refers to the same pointer as the caller's argument, so the caller will see that change to the new value. So, assuming the rest of the logic is correct, this will update a pointer within the tree to point to the new node, as you want.

这篇关于c ++指针和指向引用的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆