Return a “NULL” object if search result not found

前端 未结 8 2255
一个人的身影
一个人的身影 2020-11-28 02:23

I\'m pretty new to C++ so I tend to design with a lot of Java-isms while I\'m learning. Anyway, in Java, if I had class with a \'search\' method that would return an object

8条回答
  •  误落风尘
    2020-11-28 03:06

    As you have figured out that you cannot do it the way you have done in Java (or C#). Here is another suggestion, you could pass in the reference of the object as an argument and return bool value. If the result is found in your collection, you could assign it to the reference being passed and return ‘true’, otherwise return ‘false’. Please consider this code.

    typedef std::map OPERATORS_MAP;
    
    bool OperatorList::tryGetOperator(string token, Operator& op)
    {
        bool val = false;
    
        OPERATORS_MAP::iterator it = m_operators.find(token);
        if (it != m_operators.end())
        {
            op = it->second;
            val = true;
        }
        return val;
    }
    

    The function above has to find the Operator against the key 'token', if it finds the one it returns true and assign the value to parameter Operator& op.

    The caller code for this routine looks like this

    Operator opr;
    if (OperatorList::tryGetOperator(strOperator, opr))
    {
        //Do something here if true is returned.
    }
    

提交回复
热议问题