参考参数和递归

Reference parameters and recursion?

本文关键字:递归 参数 参考      更新时间:2023-10-16

im当前正在递减递归,并且想知道是否可以更改参考参数并在函数中给出不同的值,以及当递归返回返回相同函数时,值会更改值。这是我的问题,因为它没有编译。这是一个示例:

bool findnum_recur (int wanted, int & num)
{
    // if i want to increment num and call the function recursively   
    /*like this : */
    findnum_recur (wanted, num+1);
    // its giving me error, why and is there an alternative way
 }   

在这种情况下不是。 num+1是一个rvalue,对非const对象的引用将不会绑定到rvalues。

将递归电话更改为:

int new_num=num+1;
findnum_recur (wanted, new_num);

这会没事的。关于递归电话中的参考文献没有什么特别的或神秘的。在这方面,参考参数的作用与任何其他参数没有不同的作用。

另外,您可以将递归功能更改为:

bool findnum_recur (int wanted, const int & num)

这将结合到rvalue参数。

findnum_recur(wanted, ++num);

lvalue参考不能绑定到 +返回的rvalue。

参考参数必须引用变量。num+1不是变量,这是错误消息的来源。

在递归函数中使用参考参数非常好;如果您对要完成的工作有任何暗示,那么您可能会在这里帮助您。