1

I initialized a test case as a global variable, here:

void InsertNode(BSTNode* &t, const int &key) {
    if (t == NULL) {
        t = new BSTNode;
        t->key = key;
        t->left = t->right = NULL;
    } else {
        if (key != t->key) {
        if (key < t->key)
                InsertNode(t->left, key);
            else
                InsertNode(t->right, key);
        }
    }
}

BSTNode t1[] = {
 {4, &t1[1], &t1[2]},
 {2, &t1[3], &t1[4]},
 {6, &t1[5], &t1[6]},
 {1, NULL, NULL},
 {3, NULL, NULL},
 {5, NULL, NULL},
 {7, NULL, NULL}
};

int main() {
    InsertNode(t1, 0);
    return 0;
}

However, when I try to modify t1, it gives me an error:

invalid initialization of non-const reference of type 'BSTNode*&' from a temporary of type 'BSTNode*'

Could someone explain this for me? Thank you!!

4

1 回答 1

1

问题是您的函数声明它可能会更改指针:

void InsertNode(BSTNode* &t, const int &key) {

它将非常量指针的引用作为参数,因此它有可能修改该指针。但是,当您执行此调用时:

InsertNode(t1, 0);

您正在传递一个不可修改的指针,因为 t1 是一个数组。数组可以像指针一样使用,但不能让指针指向其他地方。

解决此问题的一种方法是具有两个不同的功能:

void InsertNode(BSTNode* &t, const int &key);

void AddNode(BSTNode* t, const int &key) {
    assert(t!=NULL);
    if (key != t->key) {
    if (key < t->key)
            InsertNode(t->left, key);
        else
            InsertNode(t->right, key);
    }
}

void InsertNode(BSTNode* &t, const int &key) {
    if (t == NULL) {
        t = new BSTNode;
        t->key = key;
        t->left = t->right = NULL;
    } else {
        AddNode(t,key);
    }
}

然后打电话

AddNode(t1, 0);
于 2013-02-04T04:22:58.503 回答