gpt4 book ai didi

c++ - 在函数中使用 bool 值 "recursiveCall"参数是一种好习惯吗?

转载 作者:行者123 更新时间:2023-11-28 01:20:28 24 4
gpt4 key购买 nike

我有一个调用自身的函数,但为了避免函数调用自身时的无限递归,我传递了一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com