简体   繁体   中英

Binary Search Tree - search function return object (C++)

//Node.cpp

Node::Node(DataType Item):item(Item)
{
    lchild = 0;
    rchild = 0;
}

DataType Node::getItem()
{
    DataType anItem = item; 
    return anItem;
}

void Node::setItem( const DataType & data)
{
    item = data;
}

Node* Node::getLChild() const
{
    Node * p = lchild;
    return p;
}

void Node::setLChild(Node * p)
{
    lchild = p;
}

Node* Node::getRChild() const
{
    Node * p = rchild;
    return p;
}

void Node::setRChild(Node * p)
{
    rchild = p;
}

Node::~Node()
{
}

//BST.cpp

DataType * BST::Search(const string name)
{
    return Search(name, root);
}

DataType * BST::Search(const string name, Node * r)
{
    if(r != 0)
    {
        if (name.compare(r->getItem().getname()) == 0)
            return &(r->getItem());
        else
        {
            if (name.compare(r->getItem().getname()) < 0)
                return Search(name, r->getLChild());
            else
                return Search(name, r->getRChild());
        }
    }
    else
        return NULL;
}

//main.cpp

    MyClass mc1("Tree","This is a tree");
    MyClass mc2("Book","This is a book");
    MyClass mc3("Zoo","This is a zoo");

    BST tree;
    tree.Insert(mc1);
    tree.Insert(mc2);
    tree.Insert(mc3);

    MyClass * mc = tree.Search("Book");
    if (mc != NULL)
        cout << mc->getname() << endl;

The problem is at the MyClass object (mc) returned from Search function.

I trace into Search() and make sure "r->getItem()" get what I want.

anything wrong with "return &(r->getItem());" ?

Thanks!

++++++

I'm a little bit confused.. can I change to "DataType BST::Search(const string name)" instead of "DataType * BST::Search(const string name)"....it seems that the compiler cannot pass. the return NULL will have some problem...

but I try your method to change the DataType* Node::getIthem() it still have error....@@

I am guessing that Node::getItem() returns a DataType by value:

DataType Node::getItem();

When you take the address of that return value, you are essentially taking the address of something that will immediately disappear (a temporary). I suspect that Node holds DataType objects internally, in which case Node::getItem() could return a pointer to one of these.

DataType* Node::getItem() { return &item; }
const DataType* Node::getItem() const { return &item; }

or return by reference:

DataType& Node::getItem() { return item; }
const DataType& Node::getItem() const { return item; }

return &(r->getItem()); will return the memory adress to whatever r->getItem() returns, not the object itself. If r->getItem() returns a pointer you will have to return (r->getItem()); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM