指向根的二叉树指针需要被引用和解引用.为什么



我的问题是为什么我需要解引用和引用一个指针下面的代码工作?ref/deref不是互相抵消的吗?如果有人能像我五岁一样解释一下,我会很感激的:)

代码:

template <typename T> 
class binNode {
private:
    T key;
public:
    binNode * left;
    binNode * right;
    binNode * parent;
    binNode() {
        this->left = NULL;
        this->right = NULL;
        this->parent = NULL;
    }
    // arg constructor:
    binNode (T key) {
        this->key = key;
        this->left = NULL;
        this->right = NULL;
        this->parent = NULL;
    }
    T getKey() {
        return this->key;
    }
    void setKey(T key) {
        this->key = key;
    }
};
template<typename T> class Tree {
private:
    binNode <T> *root;
public:
    Tree() {
        this->root = NULL;
    }
    Tree(binNode <T> * node) {
        node->parent = NULL;
        this->root = node;
    }
    /* THIS IS THE PART I  DON'T GET */
    void addNode(binNode<T> *&x, binNode<T> * node) { // what's up with the *&???
        if (x == NULL) {
            x = node;
            return;
        } else if (x->getKey() == node->getKey()) {
            node->left = x;
            node->parent = x->parent;
            x->parent = node;
            return;
        }
        if (node->getKey() < x->getKey()) {
            addNode(x->left, node);
        } else {
            addNode(x->right, node);
        }
    }
    void addNode(binNode<T> * node) {
        addNode(this->root, node);
    }
    binNode<T> * treeSearch(binNode<T> * x, T key) {
        if (x == NULL || key == x->getKey()) {
            return x;
        }
        if (key < x->getKey()) {
            return treeSearch(x->left, key);
        } else {
            return treeSearch(x->right, key);
        }
    }
    void printOrdered() {
        inorderTreeWalk(root);
        cout << endl;
    }
    void inorderTreeWalk(binNode<T> * node) {
        if (node != NULL) {
            inorderTreeWalk(node->left);
            cout << node->getKey() << 't';
            inorderTreeWalk(node->right);
        }
    }
};

这里是主要功能(不包括#inlude)

int main() {
    Tree<int> T (new binNode<int>(10));
    // Tree<int> T = new binNode<int>(10);
    T.addNode(new binNode<int> (11));
    T.addNode(new binNode<int> (9));
    T.addNode(new binNode<int> (8));
    T.addNode(new binNode<int> (12));
    T.printOrdered();
}

这不是对指针的引用/解引用,它是对指针的引用。这是必要的,因为……

void addNode(binNode<T> *&x, binNode<T> * node) {
    if (x == NULL) {
        x = node; // ...here...
        return;
    } else // ...

…您正在分配给参数x

如果你没有通过引用传递指针x ,你将赋值给参数的本地副本:

void addNode(binNode<T> * x, binNode<T> * node) {
    if (x == NULL) {
        x = node; // this acts on the local copy only, and thus does nothing.
        return;
    } else // ...

通过指针(没有引用),您可以获得地址的本地副本。这意味着您可以操作指针后面的值(在本例中为*x),该值将发生变化。但是如果你改变了地址本身,这个地址就会表现得像一个本地副本,并且你在离开方法后就失去了地址的改变。

最新更新