简体   繁体   English

向量迭代器覆盖运算符->

[英]Vector iterator override operator ->

I have for homework to make my own abstract class Vector. 我必须做作业来制作自己的抽象类Vector。 This vector should have iterator. 此向量应具有迭代器。 I make iterator in public part of the Vector. 我在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_]); 我相信您确实想要一个稍微修改的定义,该定义可以在向量的当前位置获取值,即return &((*v_)[position_]); if you've overloaded the operator[] of your vector class. 如果您已重载向量类的operator[] 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_]); 否则,为了访问向量的buffer_ ,必须首先取消引用向量才能到达缓冲区,即return &(v_->buffer[position_]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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