如何传递指针变量作为参考参数? [英] How to pass a pointer variable as a reference parameter?

查看:229
本文介绍了如何传递指针变量作为参考参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您具有这样的函数时,形式参数是引用,它成为实际参数的另一个名称,因此,当我们在函数内部修改形式参数时,函数外部的原始变量将被更改.

When you have a function like this, the formal parameter is a reference, it becomes another name for the actual argument, so that when we modify the formal parameter inside the function, the original variable outside the function is changed.

void add_five(int& a)
{
    a += 5;
}

int main()
{
    int number = 3;
    add_five(number);
    std::cout << number << std::endl;  // prints 8

    return 0;
}

我有一些适用于链表的代码.我将两个Node*传递给该函数.

I have some code which works on a linked lists. And I am passing two Node*s into the function.

void LinkedList::move_five_nodes(Node* ptr1, Node* ptr2) { ... }

...

void LinkedList::anotherFunction()
{
    Node* leader;
    Node* trailer;
    ...
    move_five_nodes(leader, trailer);
    ...
}

我认为leadertrailer指针变量内的右值内存地址将分配到Node*左值ptr1ptr2中.

I think that the rvalues memory addreses inside the leader and trailer pointer variables will be assigned into the Node* lvalues ptr1 and ptr2.

Node* ptr1 = leader;
Node* ptr2 = trailer;

问题在于ptr1ptr2是函数内部的独立局部变量.最初,它们指向与实际参数指针相同的位置.但是,我的函数移动了一些节点,并且在函数末尾,ptr1ptr2的值被更改.我希望这些更改也可以在原始变量leadertrailer中进行,就像引用一样.因此,即使ptr1ptr2过期,leadertrailer也应保持其位置.

The issue is that ptr1 and ptr2 are independent local variables inside the function. Initially, they point to the same place as the actual argument pointers. However, my function moves some nodes, and at the end of the function, the values of ptr1 and ptr2 are changed. I want these changes to also be in the original variables leader and trailer, just like references. So even when ptr1 and ptr2 expire, leader and trailer should go into their positions.

我该怎么做?也许将类型转换为int&指针?或者也许使用指向指针的指针?我想通过引用传递一个指针,但是我不确定该怎么做.

How would I do this? Maybe type cast the pointers into int&? Or maybe use pointers to pointers? I want to pass a pointer by reference, but I'm not sure how to do that.

推荐答案

我想通过引用传递一个指针,但是我不确定该怎么做.

I want to pass a pointer by reference, but I'm not sure how to do that.

为此,请考虑以下代码段

For this, consider the following snippet

#include <iostream>

void test(int*& t)
{
    t = nullptr;
}

int main()
{
    int* i = new int(4);

    test(i);

    if (i == nullptr)
        std::cout << "I was passed by reference" << std::endl;
}

,通过引用传递给test,其中将其设置为nullptr,程序打印:I was passed by reference.

in which is is passed by reference to test, where it is set to nullptr and the program prints: I was passed by reference.

我认为该示例应阐明如何通过引用函数来传递指针.

I think this example should make clear how to pass a pointer by reference to a function.

因此,在您的情况下,函数签名必须更改为

So in your case the function signiture must change to

void LinkedList::move_five_nodes(Node*& ptr1, Node*& ptr2) { ... }

这篇关于如何传递指针变量作为参考参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆