C++ 赋值后值可以更改吗?
我对这个问题感到困惑,不知道该怎么问。 好像-C++ 赋值后值可以更改吗?,c++,reference,linked-list,C++,Reference,Linked List,我对这个问题感到困惑,不知道该怎么问。 好像- current = head; 如果“head”的值以后发生变化,如 head = temp->next; “当前”的值也会改变吗?答案是否(除非您使用);如果磁头的值改变,电流的值不会改变 但是,;如果current和head是指针,则它们所引用的值可能会更改。例如: int a = 4; int *a1 = &a; int *a2 = a1; // now both pointers a1 and a2 have the sa
current = head;
如果“head”的值以后发生变化,如
head = temp->next;
“当前”的值也会改变吗?答案是否(除非您使用);如果磁头的值改变,电流的值不会改变 但是,;如果current和head是指针,则它们所引用的值可能会更改。例如:
int a = 4;
int *a1 = &a;
int *a2 = a1; // now both pointers a1 and a2 have the same value (ie the address of integer a) AND point to the same value (4)
*a1 = 5; // change value of a using pointer a1
printf("%i\n", *a2); // will print 5 since a2 also points to integer a and its value has thus changed. The value of a2 itself has not changed though (still pointing to the address of a)
这取决于当前的类型(以及头部的类型)
例如,在:
Node *head = get_head_from_somewhere();
Node *¤t = head;
head = head->next;
current
别名head
,因此更改head
(将其前进到下一个节点)也会影响current
。它们总是具有相同的值
事实上,尽管它们都在上面声明的范围内,assert(head==current)
将始终成功
然而
Node *current = head;
创建一个新的独立指针,该指针刚开始指向与头部相同的位置。前进head
不会在此处更改current
。不,它不会更改。您没有说明current
实际上是什么,如果它是一个引用,那么它会更改,否则它只会复制值,对head的任何更改都不会影响current@EdChum如果当前的是一个参考,则不能更改,虽然它所指的东西可以是。它来自链表,其中current是节点类型的指针。@Nick,那么你原来问题的答案肯定是“否”。嗨,Chris,你能解释一下吗?“我有点困惑。”尼克希尔我补充了一些解释;我希望这能帮助你回答得好,我还没用过参考资料。很可能@NickHill没有使用这些,但指出这一点很好。@说实话,这没用,我知道一些参考资料,但我从未见过有人使用“*¤t”之类的东西。这实际上意味着什么?从右到左读取:current
是指向指向节点的指针(*
)的引用(&
)。因此在上面,它是对head
的引用,并且current==head
,current==head
,current->next==head->next
等都是正确的。