*&在论证中使用时的意思?

时间:2014-12-17 15:50:49

标签: c++ pointers parameters reference arguments

我想知道的是*&手段。 上下文:

功能实现如下:

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

为什么不只是使用Node& ?

由于

2 个答案:

答案 0 :(得分:3)

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

  

为什么不直接使用Node& ?

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

答案 1 :(得分:1)

您可能希望查看特定调用,其中引用指针显示其用途:

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
}
相关问题