设计模式 - c++自己编写的查找函数如果查找不到应该返回什么?
迷茫
迷茫 2017-04-17 13:31:07
0
2
638

比如自己写了一个User类,有一个函数是查找User并返回查找到的User类,但如果这个函数查找不到应该怎么处理,java可以返回null,但是cpp不能进行这样的类型转换。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
左手右手慢动作
  1. If the function return value is a pointer, you can return nullptr.

  2. If the function return value is a reference, you can generate a static object within the search function, and then return the reference of this object whenever it cannot be found.

    class User;
    class UserList;
    User &find(UserList &ul) {
      static const User user;
      // ...
    
      return user;
    }
    
  3. Usually, the above two methods are not used in this situation, because the corresponding iterator (iterator) is often designed when designing the UserList class, so that the return value of the function is the iterator. The iterator exists to point to the one-past-last element, that is, it cannot be found. For example for vector class:

    vector<int> vi;
    vi.end();  // one-past-last iterator

    The corresponding search function is:

    vector<int>::iterator find(vector<int> &vi);
    
    auto it = find(vi);
    if (it != vi.end()) {
      /* ... */
    } 
Peter_Zhu

I also mention two methods

1. Throw exception

User& find( ... ) 
{
    ...
    if (not found) {
        UserNotFoundException().throw();    //在函数调用外部try.catch,跟java类似
    }
}

2. Multiple return values

Return values ​​can be created using functions like make_tuple, make_pair

std::pair<User, bool> find( ... ) 
{
    ...
    if (found) {
        return make_pair(..., true);    //在外部检查返回值 !不过只能返回拷贝!
    }
}

In fact, iterators and pointers are a good solution, and exceptions are also a good solution. The results can be judged as easily as the return value. However, exceptions are rarely designed when writing C++ code.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template