简体   繁体   中英

Default values to reference, c++

So I've made a linked list which holds REFERENCES for class objects I created.

I want to do a method which searches in the linked list and returning a const reference to the object if it exists, or else, if object doesn't exist, returns SOME VALUE.

which value should it be? if it was int, I'd return 0, if it was pointer, I'd return NULL....

const Node& NodeList::NodeNumSearch(int num) const
{
    Member *TempHead=MemberHead;
    while(TempHead!=NULL)
    {
        if(TempHead->GetNode().getNum() == num)
            return TempHead->GetNode();
        TempHead=TempHead->GetNext();
    }

    return ???;
}

PS a Member object is a member of the linked list. and a Node object is the value in the Member objects of the linked list.

Either throw an exception in this case, or change your function to return by pointer instead. There just isn't a sane way to return an "empty" reference here.

Alternately take the standard library approach and return an interator-like proxy by value, and you can then check it for end ness.

You could define your own NullNode as a static member var and return it.

// header
class NodeList
{
    .....

    static Node k_NullNode;
};


// cpp
/* static */ Node NodeList::k_NullNode; // you might need to pass a special argument to make it different from normal nodes.

const Node& NodeList::NodeNumSearch(int num) const
{
    ....

    return k_NullNode;
}

// test
void test()
{
    const Node& ret = NodeNumSearch(0);
    if( ret == NodeList::k_NullNode ) // you might need to override == operator.
    {
        // failed to search..
    }
    else
    {
        // succeeded..
    }
}

I think in C/C++, typically you pass a pointer to hold the result, and actually return a value based on whether or not the function worked. Alternatively, you should throw an exception if it doesn't work rather than pass back a default object. Only pass defaults back if you expect you want that default to be used by other code - for a search that seems unlikely.

// Inject Node pointer to hold the reference
// Returns 1 if it worked, 0 otherwise
const int NodeList::NodeNumSearch(int num, Node* node) const
{
  //your code here
}

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