求解一段STL源码问题
都知道单单返回值不同的两个方法不能形成重载,但STL的map却有这么一段代码,求解。。。
// [23.3.1.3] map operations /** * @brief Tries to locate an element in a %map. * @param x Key of (key, value) %pair to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after %pair. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } /** * @brief Tries to locate an element in a %map. * @param x Key of (key, value) %pair to be located. * @return Read-only (constant) iterator pointing to sought-after * element, or end() if not found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns a constant * iterator pointing to the sought after %pair. If unsuccessful it * returns the past-the-end ( @c end() ) iterator. */ const_iterator find(const key_type& __x) const { return _M_t.find(__x); }
http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.5/a01033_source.html
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
赞成楼主的观点~
find(
const
key_type& __x)
find(
const
key_type& __x)
const
我觉得它们分别被翻译成了:
find(map * const this,const key_type& __x)
find(map const * const this,const key_type& __x)
我做过实验的,this指针是不能指向其他同类指针的,说明指针本身是const的,再加上成员函数后面的
const后连this指针指向的内容也是const的,所以我觉得它们应该是被编译成我说给出的答案。
引用来自“RickHuang”的答案
在C++的类成员函数中,一般第一个变量是隐藏的this(也有编译器是将this放在最后一个参数,无论如何反正有个this的参数就是了...),所以在编译阶段时:
find(const key_type& __x)翻译为find(map* this,const key_type& __x)
find(const key_type& __x)翻译为find(const map* this,const key_type& __x)
引用来自“starstroll”的答案
引用来自“zhaowenwei”的答案
find(
const
key_type& __x)
find(
const
key_type& __x)
const
关键是后面的const
引用来自“zhaowenwei”的答案
find(
const
key_type& __x)
find(
const
key_type& __x)
const
关键是后面的const
在C++的类成员函数中,一般第一个变量是隐藏的this(也有编译器是将this放在最后一个参数,无论如何反正有个this的参数就是了...),所以在编译阶段时:
find(const key_type& __x)翻译为find(map* this,const key_type& __x)
find(const key_type& __x)翻译为find(const map* this,const key_type& __x)
同意楼上.
分享一点:
重载只是说函数名相同会形成重载,但没说何时是错误.
对于函数模板特化的函数和普通函数是可以同时存在的(2者,返回值,参数列表完全一样,但不会报错.) 这时编译器会优先调用普通函数.
find(
const
key_type& __x)
find(
const
key_type& __x)
const
关键是后面的const
zhaowenwei的答案帮我找到了答案,那const的确是关键但没有给出完整答案。