C ++技巧与*和它是什么意思

c++ trick with *& what does it mean?

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

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

我是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 *& - 星号和与号,为了什么?

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

它是

对指针的引用。与任何常规引用一样,但基础类型是一个指针。

在引用之前,逐个引用的指针必须使用双指针来完成(一些有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

希望很清楚,foo() 中的 p 确实是对 main() 中指针q的引用。

这不是

一个技巧,它只是类型——"引用指向Node的指针"。

n->insertmeSort((Node *&)first);调用insertmeSort,结果是将first转换为Node*&

void Node::insertme(Node *&to)声明insertme将指向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;
}

*& 表示您正在通过引用传递指针。 因此,在本例中,您通过引用此函数来传递指向对象的指针。 如果没有引用,此行将不起作用

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

}