简体   繁体   English

指针和c ++中的引用作为参数

[英]Pointer and references in c++ as arguments

What does this do exactly? 这究竟是做什么的?

void insertar (struct pila *&p);

What are advantages of using *& versus if the method were only declared like so: 使用*& vs的优点是,如果方法只是这样声明:

void insertar (struct pila *p);

or like so: 或者像这样:

void insertar (struct pila &p);

I know that the * is pointer and & is address, but both in the method signature? 我知道*是指针和&是地址,但是在方法签名中都是?

what is the advantage? 有什么好处?

And what are they used for? 它们用于什么?

What does it do? 它有什么作用?

You're mixing up two meanings of & . 你混淆了&两个含义。 It is the "address of" operator when used in an expression. 在表达式中使用时,它是“地址”运算符。 That is, if you have an int x; 也就是说,如果你有一个int x; and you do &x , you get the address of x . 你做&x ,你得到x的地址。 However, in a type, the & means that it is a reference type. 但是,在类型中, &表示它是引用类型。 These are two totally separate concepts. 这是两个完全不同的概念。

The following takes a pila , copying it into the function. 以下是一个pila ,将其复制到函数中。 Modifying p will only effect the copy inside the function: 修改p只会影响函数内的副本:

void insertar(pila p);

The following takes a pila by reference, so that the object inside the function is the same one as outside. 以下通过引用获取pila ,以便函数内部的对象与外部对象相同。 Modifying p here will modify the object that was passed in: 在此处修改p将修改传入的对象:

void insertar(pila& p);

The following takes a pointer to a pila , copying the pointer into the function. 以下是一个指向pila的指针,将指针复制到函数中。 Modifying the pointer will only have an effect inside the function. 修改指针只会在函数内部产生影响。 The object it points to is the same as outside however: 它指向的对象与外部相同:

void insertar(pila* p);

The following takes a pointer to a pila by reference, so that the pointer inside the function is the same one as outside. 下面通过引用获取指向pila的指针,以便函数内部的指针与外部相同。 If you modify the pointer , you'll modify the pointer outside too: 如果你修改指针 ,你也会在外面修改指针:

void insertar(pila*& p);

Here & is a reference. 这里&是一个参考。 A *& is pretty much like a ** . A *&非常像** It will allow you to change a pointer. 它将允许您更改指针。

int u = 3;

void change( int *& p ) {
    p = &u;
}

void main() {
    int *p;
    change( p );
    // p == &u
}

*& is a reference to a pointer in your example. *&是对示例中指针的引用。 In short, you can modify the data pointed by the pointer and the pointer itself. 简而言之,您可以修改指针指针本身指向的数据。 Example: 例:

int global1 = 0, global2 = 1;
void func(int*& p)
{
    *p = 42;
    p = &global1;
}

int main()
{
    int* p = &global2;
    func(p); // Now global2 == 42 and p points to global1 (p == &global1).
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM