[英]C++ const iterator in Vector
I am a newbie to C++. 我是C ++的新手。 So, please bear with me.
所以,请忍受我。 I was looking into the implementation of the
std::vector
class. 我正在研究
std::vector
类的实现。 I found the following 2 different implementation of the begin()
method. 我发现了
begin()
方法的以下2种不同实现。 I understand that the first one returns a RW iterator and the second one returns a read-only iterator. 我知道第一个返回一个RW迭代器,第二个返回一个只读的迭代器。 I thought that mere difference in return type is not enough for function overloading.
我认为仅返回类型的差异不足以实现函数重载。 How does this work then?
那如何运作呢?
iterator
begin()
{ return iterator(this->_M_impl._M_start); }
const_iterator
begin() const
{ return const_iterator(this->_M_impl._M_start); }
One is const
and the other isn't. 一个是
const
,另一个不是。 The const
version will be called for const std::vector
objects while the other is called for non-const std::vector
objects. 将为
const std::vector
对象调用const
版本,而为非const std::vector
对象调用另一个版本。 Also note that this also applies to const
and non-const references and pointers. 还要注意,这也适用于
const
和非const引用和指针。
More info on const
methods and overloading: 有关
const
方法和重载的更多信息:
Also relevant: 也相关:
The implicit "this" parameter is const in the second method. 在第二种方法中,隐式“ this”参数是const。 This is enough to distinguish them in overloading.
这足以区分它们的重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.