[英]Is initialized struct immutable?
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: 但是,当我尝试修改t1时,它给了我一个错误:
invalid initialization of non-const reference of type 'BSTNode*&' from a temporary of type 'BSTNode*'
Could someone explain this for me? 有人可以帮我解释一下吗? Thank you!!
谢谢!!
The problem is that your function is stating that it may change the pointer: 问题在于您的函数正在声明它可能会更改指针:
void InsertNode(BSTNode* &t, const int &key) {
it is taking a reference to a non-const pointer as a parameter, so it has the potential of modifying that pointer. 它以对非常量指针的引用作为参数,因此有可能修改该指针。 However when you do this call:
但是,当您执行此调用时:
InsertNode(t1, 0);
you are passing in a non-modifiable pointer, since t1 is an array. 因为t1是一个数组,所以您传入的是不可修改的指针。 An array can be used like a pointer, but you can't make that pointer point somewhere else.
数组可以像指针一样使用,但不能使该指针指向其他位置。
One way to deal with this would be to have two different functions: 一种解决方法是具有两种不同的功能:
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);
}
}
And then call 然后打电话
AddNode(t1, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.