简体   繁体   中英

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
        iterator 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, ie, 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, ie, return &(v_->buffer[position_]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM