簡體   English   中英

Encapsulated Iterator:operator ++重載

[英]Encapsulated Iterator: operator++ overloading

對於一個任務,我必須實現一個迭代器,它封裝另一個迭代器並執行范圍檢查。 我的函數prev(),next(),begin()和end()工作得很好,但是我無法讓運算符重載工作(在這方面沒有太多經驗)。 有趣的是,它沒有向我顯示任何錯誤,但是當我運行它時,程序崩潰了。 如果有人能找出原因,那就太棒了,非常感謝你。

這是我的代碼的一部分:

class MyIterator{
private:
    vector<int>::const_iterator myBegin;
    vector<int>::const_iterator myEnd;
    vector<int>::const_iterator currentElement;

public:
    MyIterator(vector<int>::const_iterator begin, vector<int>::const_iterator end){

        myBegin = begin;
        myEnd = --end;      //why do I get the address of the element after the last one (just some random address) without decreasing it like that??
        currentElement = begin;
    }


    bool hasNext(){
        if(currentElement == myEnd){
            return false;
        }
        else{
            return true;
        }
    }


    MyIterator& operator++(){
        if(hasNext()){
            currentElement++;
        }
            return *this;
    }

    MyIterator operator++(int)
    {
        MyIterator tmp(*this);
        ++(*this);
        return tmp;
    }

    vector<int>::const_iterator getElement(){
        return currentElement;
    }

};




int main() {

    vector<int> testVector;
    testVector.push_back(8); testVector.push_back(1); testVector.push_back(6); testVector.push_back(5);


    MyIterator * testIterator = new MyIterator(testVector.begin(), testVector.end());

    ++testIterator;
    test = *testIterator->getElement(); cout<<"++: "<<test<<endl;

    return 0;
}

我相信問題是你正在增加testIterator ,而不是MyIterator指向的testIterator

++testIterator;

你可能打算這樣做:

++(*testIterator);

如果你根本不使用指針,那么很容易避免這個錯誤。

MyIterator testIterator = MyIterator(testVector.begin(), testVector.end());

++testIterator;
int test = *testIterator.getElement(); 

cout<<"++: "<<test<<endl; // 1

暫無
暫無

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

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