【问题标题】: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
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2016-12-08
      • 2013-10-28
      • 1970-01-01
      相关资源
      最近更新 更多