将引用变量传递给函数
Passing reference variables to function
为什么引用变量在参数传递中被视为指针?
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 的地址。
相关文章:
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 类 Referention 中C++回调函数引用非静态函数
- 使用函数引用指向节点的指针删除链表中的节点?
- 解释通过从函数引用返回数组的语法
- "Class1"类"Class2"对象作为私有数据成员。如何通过"Class 2"函数引用"Class1"对象?
- 使用默认构造函数引用成员变量初始化错误
- 无法调用函数引用 c++
- 使用 decltype(this) 获取函数引用
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 从内联函数引用文件静态变量
- Boost::将sigaction函数引用绑定到实例
- 一种比函数引用更有效的方法
- 奇怪的未定义函数引用,函数调用C++不存在
- 是否可以检测绑定成员函数引用的对象是否被删除或销毁
- 构造函数引用参数导致seg错误
- 是否可以使函数模板从函数引用中获取“decltype”
- 无法让 Lua 函数引用"self"
- 如何解析变量和函数引用(Linker & Compiler)?
- 从不同模块调用函数 - 引用错误
- 如何在主函数中连接到数据库,然后从其他函数引用它