【问题标题】:What does *& mean when used in argument?*& 在参数中使用时是什么意思?
【发布时间】:2014-12-17 15:50:48
【问题描述】:
我想知道是 *& 的意思。
背景:
一个函数实现如下:
void headInsert( Node*& head, int info )
{
Node* temp = new Node(info);
temp->link = head;
head = temp;
}
为什么不只使用 Node&?
谢谢
【问题讨论】:
标签:
c++
pointers
parameters
reference
arguments
【解决方案1】:
Node*& 表示“对节点指针的引用”,而Node& 表示“对节点的引用”。
为什么不直接使用 Node& 呢?
因为headInsert函数需要改变头部指向的东西。
【解决方案2】:
您可能想查看具体的调用,其中引用指针揭示了它们的用途:
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
}