提问者:小点点

在递归函数的函数调用中修改通过引用传递的参数


下面是一个简单的代码,它将counter作为引用传递的参数,然后打印它:

  #include <iostream>
using namespace std;
void Fun(int &counter, int n)
{
    if(n==0)
      return;
    Fun(counter+1,n--);
}


int main() {
    int counter = 0;
    int n = 5;
    Fun(counter,n);
    cout<<counter<<endl;
    return 0;
}

我得到了一个错误。

  prog.cpp: In function ‘void Fun(int&, int)’:
prog.cpp:7:16: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
     Fun(counter+1,n);
                ^
prog.cpp:3:6: note:   initializing argument 1 of ‘void Fun(int&, int)’
 void Fun(int &counter, int n)
  ^

有人能帮忙吗?为什么会出错?


共1个答案

匿名用户

fun(counter+1,n--);中,您没有将counter传递给函数。 您可以创建一个临时fromcounter+1,并将其传递给函数。 为了延长临时引用的生命期,它需要是const,因此void Fun(const int&;counter,int n)将是可编译的。

但是,当函数结束时,计数器将为0,因为您从未更改Counter,而函数将永远不会返回,因为您没有减少传递给函数的n。 使用n调用函数,然后减少n

另一种选择:

void Fun(int &counter, int n)
{
    if(n==0)
      return;
    Fun(counter += 1, n - 1); // or Fun(++counter, --n);
}

counter+=1++counter都返回对counter的引用,这就是为什么这样做的原因。

但是,counter++n--将不起作用,因为后增量运算符也返回临时数,如:

int old = n;
n = n - 1;
return old;