簡體   English   中英

數組迭代器中的hasNext()方法

[英]hasNext() method in array iterator

那是我的通用數組頭文件:

#ifndef ARRAY_H
#define ARRAY_H
#include "Number.h"
#include "Iterator.h"

//array is contius memory of numbers
class Array{
protected:
    //array has some contius cell of memory each include the data
    class Cell{
    public:
        Number* m_data;

        //c'tor:(inline)
        Cell(Number* num=NULL): m_data(num){};
        //D'tor (inline)
        ~Cell(){};
    };
    //composition class of iterator:
    class ArrayIterator:public Iterator{
    public:
        Cell* m_current;

        //C'tor:(inline)
        ArrayIterator(Cell* cell):m_current(cell){};
        //D'tor:
        ~ArrayIterator(){};

        //is there any next numbers
        bool hasNext()const;
        //is there any prev numbers
        bool hasPrev()const;

        //returning the current and getforward
        Number& next();
        //returning the current and getback
        Number& prev();

    };
    Cell* m_head,*m_last;
public:
    //C'tor:
    Array(const int amount);
    //D'tor:
    virtual ~Array(){delete[]m_head;};


    //Random access operator:
    Number& operator [] (const int i)const{return *m_head[i].m_data;};


};


#endif

將Number和Iterator視為抽象類,而Number表示通用數字。

我的問題:如何在ArrayIterator中實現hasNext(),因為ArrayIterator是一個合成類,並且它不“知道”數組的大小

為了實現hasNext()hasPrev()方法, ArrayIterator需要知道要迭代的當前Array的邊界在哪里。

這可以通過將Cell* m_head,*m_lastCell* m_head,*m_last一起m_currentArrayIterator ,或者通過存儲指向Array對象的指針並安排ArrayIterator可以訪問Array對象的m_headm_last來完成。 無論哪種情況,您都需要在ArrayIterator存儲其他信息。

暫無
暫無

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

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