Return a “NULL” object if search result not found

前端 未结 8 2178
一个人的身影
一个人的身影 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:24

    You can easily create a static object that represents a NULL return.

    class Attr;
    extern Attr AttrNull;
    
    class Node { 
    .... 
    
    Attr& getAttribute(const string& attribute_name) const { 
       //search collection 
       //if found at i 
            return attributes[i]; 
       //if not found 
            return AttrNull; 
    } 
    
    bool IsNull(const Attr& test) const {
        return &test == &AttrNull;
    }
    
     private: 
       vector attributes; 
    };
    

    And somewhere in a source file:

    static Attr AttrNull;
    

提交回复
热议问题