首页 > 解决方案 > 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'

任何帮助表示赞赏

标签: c++recursion

解决方案


如果您else在第一段代码中点击分支,则不会修改任何内容f,因此它当然保持为空,并且该空字符串是您最终返回的内容。

可能希望return go(...或至少捕获返回值并对其进行处理f或直接返回它。


推荐阅读