簡體   English   中英

如何訪問標准*重載運算符后的行為*?

[英]How to access standard *this behaviour after overloading operator*?

我正在為迭代器編寫包裝器,並試圖使其表現得像所包含的迭代器一樣。

為此,它需要重載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;
    }
};

在這兩個運營商++的功能, this需要解除引用。 但看起來這將導致從重載函數而不是IteratorWrapper獲得mapPairAlias

該問題應如何解決? STL迭代器可以很好地處理這兩個函數,因此大概有一種方法。

this是指向當前實例的原始指針

*this是對當前實例的引用

**thisthis->operator*()語法糖

因此,您描述的問題不存在, *this可以滿足您的要求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM