*&在论证中使用时是什么意思?

What does *& mean when used in argument?

本文关键字:是什么 意思      更新时间:2023-10-16

我想知道是*&means。上下文:

函数的实现方式如下:

void headInsert( Node*& head, int info )
{
    Node* temp = new Node(info);
    temp->link = head;
    head = temp;
}

谁不只是使用Node&?

谢谢

Node*&表示"对指向节点的指针的引用",而Node&表示"对节点的引用"。

为什么不直接使用Node&?

因为headInsert函数需要改变头部指向的内容。

您可能需要查看特定的调用,其中引用指针揭示了它们的用法:

Node* pHead = somewhere;
headInsert(pHead, info);
// pHead does now point to the newly allocated node, generated inside headInser, 
// by new Node(info), but NOT to 'somewhere'

让我评论一下你的例子,也许这会更清楚:

void headInsert( Node*& head, int info )
{
    Node* temp = new Node(info); // generate a new head, the future head
    temp->link = head; // let the former head be a member/child of the new head
    head = temp; // 'overwrite' the former head pointer outside of the call by the new head
}