为迭代器编写解引用操作符

Writing a dereference operator for iterator

本文关键字:引用 操作符 迭代器      更新时间:2023-10-16

我正在编写一个Set类,以便了解它们的实际工作方式,并尝试编写我自己的迭代器。据我所知,迭代器只是一个抽象的高级指针,通过一个结构体进行迭代。

话虽如此,我知道迭代器的重要部分是++——和*操作。我已经成功地创建并测试了in/递减操作符,但是在定义服从Iterator时需要返回什么时,我花了很多时间。

返回它所指向的对象吗?

下面是我的set.h文件中的相关代码:
class Set{
private:
    struct Elem {
        ELEMENT_TYPE info;
        Elem *prev, *next;
    };
    Elem *_head, *_tail;
    int _size;
public:
    //...
    class Iterator{
        private:
            Elem * _cur;
    public:
        Iterator(){}
        Iterator( Elem* );
        Iterator operator++( int );
        Iterator operator++();
        Iterator operator--( int);
        Iterator operator--();
        bool operator==( const Iterator& rhs );
        bool operator!=( const Iterator& rhs );
        Elem operator*();
    };
     //...
};

就像我说的,我返回的是迭代器指向的"Elem",对吗?

Set::Elem* Set::Iterator::operator*(){
return _cur;
}

通常通过引用返回指向的元素。

Elem&       operator*()       { return *_cur; }

不过,它在一定程度上取决于迭代器的类型。某些迭代器(例如输入迭代器)不一定返回引用。

您通常会返回一个引用,如:

ELEMENT_TYPE & operator*() { return _cur->info;}

*操作符应该返回值或引用

Set::Elem &Set::Iterator::operator*() {
    return *_cur;
}
const Set::Elem &Set::Iterator::operator*() const {
    return *_cur;
}