[英]c++:return statement behaving weirdly
这是包含我代码相关部分的代码概述。
在empprint函数内部,我调用了bfs打印函数,该函数递归调用自身,直到完成打印需要打印的所有内容为止,然后应该让我回到empprint函数。 但是bfsprint中的return语句不会使我回到empprint。
我能想到的一个可能原因是bfsprint递归调用自身,因此它将仅返回调用它的最后一个bfsprint方法而不是empprint函数,但它似乎无法解决我的问题。 我陷入了执行不终止的代码。
void node::empprint(node* myroot)
{
//do something
bfsprint(c);
cout<<"pt 5"; //this cout is not reached
return;
}
void node::bfsprint(Linklist<node*> noddy)
{
// lot of code to implement breadth-first search. No issue
if(c.getHead()==NULL) cout<<"1" //this does print 1 to output
if(c.getHead()==NULL) return; //I think this should send me back to empprint
// and print "pt 5" on output but program hangs.
// instead of this happening
bfsprint(c);
}
如果有人认为这可能会受到方法中其他代码的影响,我将添加它,但我认为情况并非如此。
如果您的调用堆栈如下所示:
node::empprint
node::bfsprint
node::bfsprint
那么从最终通话返回将导致
node::empprint
node::bfsprint
因此,您仍然需要N次调用才能返回到node :: empprint。
您可以在课程中设置一个布尔值以返回,但那有点hacky ..
void node::bfsprint(Linklist<node*> noddy)
{
if ( something ) { m_unwindstack = true; }
// setting the bool to force returning early/stop recursion once m_unwindstack is true to get back to empprint
if ( m_unwindstack ) { return; }
}
编辑:顺便说一句,如果您正在使用链接列表执行任何操作,则自从传递数据副本以来,您将再也看不到更改。 您应该传递参考Linklist&。
另外,Linklist似乎是您自己的课程? 因此,如果您不使用引用,请确保其可复制,否则将发生不良情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.