Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 通过引用传递:参数6从';int';至';国际及';_C++_Pass By Reference - Fatal编程技术网

C++ 通过引用传递:参数6从';int';至';国际及';

C++ 通过引用传递:参数6从';int';至';国际及';,c++,pass-by-reference,C++,Pass By Reference,我有一个函数,我通过引用传递一个参数,因为我希望函数编辑它。这个函数在几个地方调用,我只关心在特定实例中调用时的ref值。 伪代码: test_fn(int a, int b, inc , int d, int e, int& ref) { //bunch of other functionalities //. //. ref = (a*b+c)*(d+e); } test_fn(1,2,3,4,5,0)//everywhere that I do not care about r

我有一个函数,我通过引用传递一个参数,因为我希望函数编辑它。这个函数在几个地方调用,我只关心在特定实例中调用时的ref值。 伪代码:

test_fn(int a, int b, inc , int d, int e, int& ref)
{
//bunch of other functionalities 
//.
//.
ref = (a*b+c)*(d+e);
}

test_fn(1,2,3,4,5,0)//everywhere that I do not care about ref 
int value = 0;
test_fn(1,2,3,4,5, value)//I care about value here and would use it in the remainder of the code .
为什么我不能直接通过0?我也尝试传递一个NULL,它有一个很长的int到int转换错误


为什么这是错误的?在这里实现预期结果的最佳方式是什么

为了通过引用传递变量,它必须存在,传递0或
NULL
意味着您要发送一个常量。不能编辑常量的值,因为它实际上不是变量


至于解决您的问题,您可能应该使用指针来实现这一点,然后检查指针是否设置为0,
NULL
,或者如果您使用C++11,
nullptr
常规的
int&
意味着它已经需要分配给一个变量;它需要是一个
左值

0
未分配给变量;它是一个“自由变量”,这意味着它不附加到标签上。这意味着它是一个
rvalue
,一个未绑定到变量的临时变量。它由
int&
表示

rvalue
s可以转换为
lvalue
s,如果将其设置为
const int&
。可以将常量转换为int常量的
引用
(从右向左读取)


然而,这将是毫无意义的,因为您想要修改变量;因此,答案是遵循您自己的约定,不要传入那些尚未“存在”且绑定到标签/名称的内容,如常量或移动变量。

考虑以下更简单的示例:

test_fn(int& ref)
{
    ref = 3;
}
int main() {
    test_fn(0);
}
这实际上是试图将0设置为3。i、 e:

int main() {
    0 = 3;
}
但那是胡说八道。
int&
(与
const int&
相反)只能接受可修改的内容


(正如@nogeek001所指出的,
const int&
无论如何都不允许我们修改ref。)

ref是一个引用,而不是指针。如果是,则可以传递0,表示指向null的指针;引用不能指向任何内容,必须绑定到左值。

正如其他人所说,不能将文本作为引用传递

您可以做的是传递地址,然后检查函数中的地址是否为空:

test_fn(int a, int b, inc , int d, int e, int* ref)
{
    int someValue = (a*b+c)*(d+e);
    if ( ref )
       *ref = someValue;
}
//...
test_fn(1,2,3,4,5,0);
int value = 0;
test_fn(1,2,3,4,5, &value)

如果您希望传递NULL作为一个选项,您是否考虑过在引用上使用指针?(相对于常量int&)?使用常量int&但是不会让函数修改ref值-正确吗?