重载operator *后如何访问标准*这种行为?

时间:2014-05-30 18:18:07

标签: c++ operator-overloading

我正在为迭代器编写一个包装器,并尝试使其行为与包含的迭代器一样。

为此,它需要重载operator *和operator ++,但这会产生以下问题:

//Typedefs to make below code easier to read
typedef std::map::const_iterator<std::string, SomeClass> iteratorAlias;
typedef std::pair<const std::string, SomeClass> mapPairAlias;

class IteratorWrapper
{
    iteratorAlias iterator;

    /*Other code omitted*/

    mapPairAlias& operator*()
    {
        return *iterator;
    }

    const mapPairAlias& operator*() const
    {
        return *iterator;
    }

    IteratorWrapper& operator++()
    {
        ++this->iterator;
        return *this;
    }

    IteratorWrapper operator++(int)
    {
        IteratorWrapper copy(*this);
        ++(*this);
        return copy;
    }
};

在两个operator ++函数中,this都需要取消引用。但看起来这会导致从重载函数中获取mapPairAlias,而不是IteratorWrapper

如何解决此问题? STL迭代器处理这两个函数都很好,所以可能有一种方法。

1 个答案:

答案 0 :(得分:4)

this是指向当前实例的原始指针

*this是对当前实例的引用

**thisthis->operator*()

的语法糖

所以你描述的问题不存在,*this会做你想要的事情。

相关问题