作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个调用自身的函数,但为了避免函数调用自身时的无限递归,我传递了一个 bool 变量,这样它就不会再次调用自身。然而,这也意味着使用我的代码的人可以使用该函数并向其传递一个 true
参数。
class Test
{
public:
static bool doCheck(int x, bool recursiveCall = false)
private:
int m_array {10, 5, 3, 25, 12, 0, -6};
int tracker = 0;
};
bool Test::doCheck(int x, bool recursiveCall)
{
if (m_array[tracker] > x)
{
//do stuff
++tracker;
return true;
}
else if (!recursiveCall)
{
// reset tracker
tracker = 0;
return doCheck(x, true);
}
return false;
}
int main()
{
Test::doCheck(2); // returns true, m_array[tracker] now equals 5
// The next call will go through the "else if" part which will reset the tracker
// and return false, if we didn't call the function as recursive it would call itself infinitely !
Test::doCheck(50);
return 0;
}
编辑:根据要求,我提供了一个更好的例子。当然我们可以在再次调用 doCheck() 之前执行 m_array[tracker] > x
但这意味着我们的检查将完成两次,如果我们使用更复杂的算法检查某些东西可能会有问题
这样做是好的做法吗?
最佳答案
不,这是个坏主意。而是重新编写您的基本案例,以便它始终自行停止。
你的例子永远不会明智地递归,所以它也可能是
void foo(int x)
{
if (x > 10)
{ /* Do stuff here */ }
}
关于c++ - 在函数中使用 bool 值 "recursiveCall"参数是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528267/
我有一个调用自身的函数,但为了避免函数调用自身时的无限递归,我传递了一个 bool 变量,这样它就不会再次调用自身。然而,这也意味着使用我的代码的人可以使用该函数并向其传递一个 true 参数。 cl
我是一名优秀的程序员,十分优秀!