这是一个简单的代码,它将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)
^
有人可以帮忙,为什么会出现此错误?
在Fun(counter+1,n);
中,您没有将counter
传递给函数。您可以通过counter+1
创建一个临时函数并传递给该函数。为了延长通过引用获取的临时生存期,它必须为const
,因此void Fun(const int &counter, int n)
将是可编译的。
但是,当函数结束时,计数器将为0
,因为您从不更改计数器,并且由于不减小n
,所以函数将永不返回。
替代:
void Fun(int &counter, int n)
{
if(n==0)
return;
Fun(counter += 1, n - 1); // or Fun(++counter, n - 1);
}