【发布时间】: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