可以将指针的引用作为函数参数传递吗?

Tes*_*ser 1 c++ c++17

我的理解是,在 C++ 中 & 和 * 相互抵消,即 int *&p 本质上等于 p 作为其在整数 p 地址处的值。

现在,鉴于上述情况,传递对指针的引用是否有效,即说我试图将对指针的引用作为函数中的参数传递,如下所示?

void func(int* &p)
Run Code Online (Sandbox Code Playgroud)

上面的结果不会导致用 & 取消 * 并且只是 int p 吗?如果我尝试以类似的方式传递对类对象指针的引用,它有多正确?

#include <iostream>

using namespace std;

int gobal_var = 42;

// function to change Reference to pointer value
void changeReferenceValue(int*& pp)
{
    pp = &gobal_var;
}

int main()
{
    int var = 23;
    int* ptr_to_var = &var;

    cout << "Passing a Reference to a pointer to function" << endl;

    cout << "Before :" << *ptr_to_var << endl; // display 23

    changeReferenceValue(ptr_to_var);

    cout << "After :" << *ptr_to_var << endl; // display 42

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

And*_*zel 6

您是正确的,当在表达式&中使用时,寻址运算符和*间接运算符会相互抵消。

然而,当在声明内部使用时,这些运算符具有非常不同的含义。在声明中,*表示“指针”,&表示“引用”。因此,当在声明中使用时,它们不会相互抵消。

类型的对象int*&只是对指向 的指针的引用int