0

可能重复:
指向引用的指针和指向指针的引用之间的区别

我是 C++ 的新手,我从事一个非常复杂的项目。当我试图弄清楚一些事情时,我看到了一件有趣的事情:

n->insertmeSort((Node *&)first);

当我们深入insertmeSort时,我们可以看到同样的情况:

    void Node::insertme(Node *&to)
{
   if(!to) {
      to=this;
      return;
   }
   insertme(value>to->value ? to->right : to->left);
}

所以我的问题的原因是:Node *&- 星号和&符号,为了什么?

它看起来很棘手,对我来说很有趣。

4

3 回答 3

1

它是对指针的引用。像任何常规引用一样,但底层类型是指针。

在引用之前,必须使用双指针来完成逐个引用的引用(一些具有 C 思想的人仍然这样做,我偶尔也是其中之一)。

以免有任何疑问,试试这个真正沉入其中:

#include <iostream>
#include <cstdlib>

void foo (int *& p)
{
    std::cout << "&p: " << &p << std::endl;
}

int main(int argc, char *argv[])
{
    int *q = NULL;
    std::cout << "&q: " << &q << std::endl;
    foo(q);

    return EXIT_SUCCESS;
}

输出(你的值会不同,但是 &p == &q)

&q: 0x7fff5fbff878
&p: 0x7fff5fbff878

希望很清楚pinfoo()确实是对指针qin的引用main()

于 2012-11-30T04:27:11.863 回答
1

这不是技巧,它只是类型——“对指针的引用Node”。

n->insertmeSort((Node *&)first);调用insertmeSort结果first为 a Node*&

void Node::insertme(Node *&to)声明insertme将指向 a 的指针的引用Node作为参数。

引用和指针如何工作的示例:

int main() {
    //Initialise `a` and `b` to 0
    int a{};
    int b{};
    int* pointer{&a}; //Initialise `pointer` with the address of (&) `a`
    int& reference{a};//Make `reference` be a reference to `a`
    int*& reference_to_pointer{pointer_x}; 

    //Now `a`, `*pointer`, `reference` and `*reference_to_pointer`
    //can all be used to manipulate `a`.
    //All these do the same thing (assign 10 to `a`):
    a = 10;
    *pointer = 10;
    reference = 10;
    *reference_to_pointer = 10;

    //`pointer` can be rebound to point to a different thing. This can
    //be done directly, or through `reference_to_pointer`.
    //These lines both do the same thing (make `pointer` point to `b`):
    pointer = &b;
    reference_to_pointer = &b;

    //Now `b`, `*pointer` and `*reference_to_pointer` can
    //all be used to manipulate `b`.
    //All these do the same thing (assign 20 to `b`):
    b = 20;
    *pointer = 20;
    *reference_to_pointer = 20;
}
于 2012-11-30T04:27:22.977 回答
0

*& 表示您通过引用传递指针。所以在这种情况下,你通过引用这个函数来传递一个指向对象的指针。没有参考,这条线将没有效果

if(!to) {
  to=this;
  return;

}

于 2012-11-30T04:31:51.583 回答