C++递归不返回任何内容

C++ recursion returns nothing

本文关键字:任何内 返回 递归 C++      更新时间:2023-10-16
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);
        }
    }
}

我收到访问违规,因为我没有回报,如果我添加返回 ";最后,它只返回任何内容,而不是"e">

任何帮助表示赞赏

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

您可能希望return go(...或至少捕获返回值,并对其执行涉及f或直接返回它的操作。