I am trying to create specific iterators for specific items in an aggregate.
class Item {
public:
Item(string name, int type, double price) {
this->name = name;
this->type = type;
this->price = price;
}
string GetName() { return this->name;}
int GetType() { return this->type;}
private:
string name;
int type;
double price;
};
class Food : public Item {
public:
Food(string name, double price) : Item(name, 1, price) {}
private:
};
I have a specific iterator to show only food.
class Iterator {
public:
virtual void First() = 0;
virtual void Next() = 0;
virtual bool IsDone() = 0;
virtual Item *CurrentItem() = 0;
protected:
Iterator(){};
};
class FoodIterator : public Iterator {
public:
FoodIterator(Aggregate* aggregate) {
this->aggregate = aggregate;
current = 0;
};
void First() { current = 0;}
void Next() {
Item* temp = aggregate->Get(current);
while (temp->GetType() != 1) {
current++;
}
}
Item *CurrentItem() {
if (IsDone()) { return NULL; }
else {
return aggregate->Get(current); }
};
bool IsDone() {
if (current >= aggregate->GetCount() ) { return true;}
else {return false;}
};
private:
Aggregate *aggregate;
int current;
};
and this is my printing function.
void printAggregate(Iterator *i) {
cout << "Iterating list: " << endl;
for (i->First(); !i->IsDone(); i->Next()) {
cout << "Current Item -> " << i->CurrentItem()->GetName() << endl;
}
}
and this is my main.
Aggregate *list = new ConcreteAggregate();
list->Add(new Food("Bread" , 1));
list->Add(new Food("Meat", 44.90));
Iterator *foodIterator = list->CreateIterator(1);
printAggregate(foodIterator);
It goes in an infinite loop. I think the problem is in my Next() function which is in the Iterator. But, I couldn't fix it.
Aucun commentaire:
Enregistrer un commentaire