参考参数和递归
Reference parameters and recursion?
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
不是变量,这是错误消息的来源。
在递归函数中使用参考参数非常好;如果您对要完成的工作有任何暗示,那么您可能会在这里帮助您。
相关文章:
- 打包可变参数模板具有零元素时的递归
- 使用 SFINAE 作为模板参数的编译时递归
- 为什么我的递归可变参数模板无法编译?
- 为什么当函数参数未定义为常量引用时存在无限递归?
- 使用参数推导时如何停止模板递归?
- 使用带有一个参数函数的递归找到数字的平方
- 作用于可变类模板参数的递归函数
- 对可变参数函数的递归调用的链接器错误
- 如何将从第 2 个字符开始的字符串作为函数中的参数传递以进行递归,并约束数据 tiee 是函数中的字符串?
- C++ 引用类型作为递归函数参数
- 如何将参数递归绑定到函数?
- 递归回文检查,不使用向量、大小或其他参数
- n维向量的递归可变参数模板函数
- 没有参数的递归,也没有静态或全局变量
- 循环访问多个模板参数的递归模板函数
- 具有编译问题的简单(递归)可变参数模板"accumulate_for"函数
- 递归、可变参数模板函数
- 折叠表达式、参数包扩展、类成员函数中的递归
- 可变参数模板中递归模板函数的终止问题
- 如果带有递归参数包的 constexpr