这是我第一次尝试在c ++程序中处理多个类,并且体验真的很糟糕,因为我花了数十个小时只是盯着代码并试图找出问题所在。另外,我的实际代码目前大约有600行,因此我将把相关代码放到最令我困扰的地方,然后尝试解释一下。

我有一个称为节点的多路搜索树的类。我的目标是使用AVL树(类名Avlnode)作为索引树(包含单词的排序顺序以及每个Avlnode上相应节点的地址),以便在O( log n)时间。
现在考虑这个代码片段

//Basically searches for a string in Avl tree with root t and returns pointer
//to the   corresponding node in the multi-way tree

node* Avlnode::Avlsearch(string x,Avlnode* t)
{
    if (t==NULL)
    {
        cout<<"why you search whats not in string";//invalid search
        exit(0);
    }
    else
    {
        if(isLess(x,t->element)) //isLess compares strings and works good
        {                        //element refers to the string stored in Avlnode
            Avlsearch(x,t->left);
        }
        else if (isLess(t->element,x))
        {
            Avlsearch(x,t->right);
        }
        else
        {
            cout<<"found";
            cout<<t->index->empname;
            return t->index; //its fine till here
        }
    }
}

//basically adds child under the boss in multi-way tree, by searching for the
//address of boss first using the AVL tree

void node::insertunderboss(string child, string boss,Avlnode* obj1)
{
    node* temp=obj1->Avlsearch(boss, obj1->root); //root=root of Avltree
//why is address of temp and t->index not the same??
    cout<<temp;
    cout<<"root current is "<<obj1->root->element;
    cout<<"\n"<<temp->empname; //empname is string stored in node
 //this refuses to work even though t->index->empname worked perfect.
 // in my first function t->index->empname gave me a string
 // I just stored t->index inside temp
 //But temp->empname makes cmd hang. Your program has stopped working.
    node* c=insertemp(child,temp);
    cout<<"last check";
    obj1->Avlinsert(c,obj1->root);
    return;
}


我希望我的问题很清楚。我本来想通过引用传递,但我无法弄清楚为什么它不起作用,从逻辑上看还可以。
任何形式的帮助将非常感激。

最佳答案

看起来您丢失了return语句,这是一个改进

node* Avlnode::Avlsearch(string x,Avlnode* t)
{
    if (t==NULL)
{
    cout<<"why you search whats not in string";//invalid search
    exit(0);
}
else
{
    if(isLess(x,t->element)) //isLess compares strings and works good
    {                        //element refers to the string stored in Avlnode
        return Avlsearch(x,t->left);
        ^^^^^^
    }
    else if (isLess(t->element,x))
    {
        return Avlsearch(x,t->right);
        ^^^^^^
    }
    else
    {
        cout<<"found";
        cout<<t->index->empname;
        return t->index; //its fine till here
    }
}
}

09-11 17:34