将引用变量传递给函数

Passing reference variables to function

本文关键字:函数 引用 变量      更新时间:2023-10-16

为什么引用变量在参数传递中被视为指针?

int x; 
void fun(&x);
void fun(int* y)
{
    ------some code----
}

在这里,变量x的引用被传递给fun()函数。fun() 中的局部变量y包含变量x的引用,但y声明为指针。为什么?

你错了&x它不是"参考变量"。它是指向x的指针,&地址运算符,它返回给定的任何参数的地址(即指针(。

这很令人困惑,因为&用于表示类型声明中的引用,但它在表达式中的含义是不同的。

例如

int x;
int& y = x; // here & means reference because 'int&' is a type declaration
int* z = &x; // here & means address-of because '&x' is an expression

虚空乐趣(&x(;

在这一行中&X是"不是引用变量",即X变量的地址。

例:

int y ; int &z = y;//here &z is reference variable(a reference must initialized when it is created)

这里: void fun(&x);您正在将变量 x 的地址(而不是引用(传递给 void fun(int* y) 。由于int* y是一个指针,因此它指向 x 的地址。