【问题标题】:Modifying Arguments passed by reference in the function call in a recursive function在递归函数的函数调用中修改通过引用传递的参数
【发布时间】:2020-06-14 11:02:54
【问题描述】:

这是一个简单的代码,它将 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)
  ^

有人可以帮忙吗,为什么会出现这个错误?

【问题讨论】:

    标签: c++ recursion reference rvalue lvalue


    【解决方案1】:

    Fun(counter+1,n--); 中,您没有将counter 传递给函数。您从 counter+1 创建一个临时文件,并将其传递给函数。要延长临时引用的生命周期,它需要是const,所以void Fun(const int &amp;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--工作,因为 post-increment 运算符也返回临时值,如:

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

    【讨论】:

    • 这将导致无限递归,因为n 的相同值被传递给递归调用。
    猜你喜欢
    • 2018-03-07
    • 2020-10-02
    • 2019-02-12
    • 2014-05-05
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多