c++ - C++ 递归不返回任何内容
问题描述
string go(string s, int& ind, node* cur,char &c)
{
string f = "";
if (cur->leftChild == NULL && cur->rightChild == NULL)
{
f = cur-> content;
}
else
{
if (s[ind] == 0x30)
{
ind++;
go(s, ind, cur->leftChild,c);
}
else
{
ind++;
go(s, ind, cur->rightChild,c);
}
}
return f;// breakpoint here shows correct value 'e'
}
...
int main()
{
string h = "";
int ind = 0;
string h = go(s, ind, &glob_root,c);
cout << h << endl; // h is blank.
}
事实证明,第一次在 f 命中断点时,它显示的值为 'e',这是我想要的,但是在接下来的命中时它会变为空白。
如果我将其更改为
string go(string s, int& ind, node* cur,char &c)
{
if (cur->leftChild == NULL && cur->rightChild == NULL)
{
return cur-> content;
}
else
{
if (s[ind] == 0x30)
{
ind++;
go(s, ind, cur->leftChild,c);
}
else
{
ind++;
go(s, ind, cur->rightChild,c);
}
}
}
我得到一个访问冲突,因为我没有返回,如果我添加 return ""; 最后,它什么也不返回,而不是'e'
任何帮助表示赞赏
解决方案
如果您else
在第一段代码中点击分支,则不会修改任何内容f
,因此它当然保持为空,并且该空字符串是您最终返回的内容。
您可能希望return go(...
或至少捕获返回值并对其进行处理f
或直接返回它。
推荐阅读
- vue.js - 组件渲染函数Vuejs中的无限更新循环
- javascript - 如何将数据从父组件发送到特定的动态创建的子组件?
- r - 编写一个 R 函数,但是如何修改它以遍历数据框中的列并遍历多个数据集?
- bluetooth - 捕获进出计算机的蓝牙流量
- textarea - 如何更改 textarea 中的点击行为,使其显示光标位置并且不选择字符?
- swift - 为什么 AVPlayer 不能使用通过 FileManager 找到的 URL?
- javascript - 如何在 p5.js 中加载图像并将其作为背景
- java - 编译错误'The Method setRadius(int) is undefined for the type Shape'
- c# - 单击条目时 Xamarin.Forms 应用程序崩溃,返回“NullReferenceException”
- javascript - 谷歌表格图表中的标题有非常不稳定的鼠标滚轮滚动