C ++:在处理多个类时感到困惑

时间:2013-09-13 20:11:11

标签: c++ data-structures avl-tree

这是我第一次尝试在c ++程序中处理多个类,而且经验非常糟糕,因为我花了好几十个小时才盯着代码并试图弄清楚什么是错误的。另外,我的实际代码目前大约有600行,所以我会把相关的代码放到最困扰我的地方并尝试解释。

我正在为一个名为node的多路搜索树创建一个类。我的目标是使用AVL树(类名Avlnode)作为索引树(在每个Avlnode中包含排序顺序的单词和相应节点的地址),以便在O中的多路树上进行操作(记录时间。 现在考虑这段代码片段

//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;
}

我希望我的问题很明确。我想通过引用传递,但我无法弄清楚为什么这不起作用,逻辑上它看起来没问题。 任何形式的帮助都会非常感激。

1 个答案:

答案 0 :(得分:3)

看起来你缺少返回语句,这是一个改进

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
    }
}
}