Vector iterator override operator ->
I have for homework to make my own abstract class Vector. This vector should have iterator. I make iterator in public part of the Vector. This is my code for iterator:
class iterator {
friend class Vector;
Vector* v_;
int position_;
iterator(Vector* v,int position)
: v_(v),
position_(position)
{}
public:
iterator()
: v_(0),
position_(0)
{}
iterator& operator++() {// pre
position_++;
return *this;
}
iterator operator++(int) {//post
iterat开发者_开发知识库or res=*this;
position_++;
return res;
}
T& operator*() {
return v_->buffer_[position_];
}
T* operator->() {
return &buffer_[position_];
}
bool operator==(const iterator& other) const {
return position_ == other.position_;
}
bool operator!=(const iterator& other) const {
return !operator==(other);
}
};
My question is if the operator -> is correct defined.
Thanks
I believe you're really wanting a slightly modified definition that gets the value at the current position of the vector, i.e., return &((*v_)[position_]);
if you've overloaded the operator[]
of your vector class. Otherwise in order to get access to the buffer_
of your vector, you have to dereference the vector first in order to get to the buffer, i.e., return &(v_->buffer[position_]);
精彩评论