1

那是我的通用数组头文件:

#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 是一个组合类,它不“知道”数组的大小

4

1 回答 1

1

要实现hasNext()andhasPrev()方法,ArrayIterator需要知道Array它正在迭代的当前边界在哪里。

这可以通过将with与Cell* m_head,*m_last一起存储,或者通过存储指向对象的指针并安排 可以访问对象的and来完成。无论哪种情况,您都需要在.m_currentArrayIteratorArrayArrayIteratorm_headm_lastArrayArrayIterator

于 2013-05-22T08:10:42.533 回答