#include <cstdlib>
#include <iostream>
#include <string>
usingnamespace std;
enum ItemEnum
{
ITEM_ROCK,
ITEM_STONE,
ITEMNUM
};
class Item
{
public:
string name;
int id;
void writename()
{
cout << name << " with ID " << id << " created." << endl;
}
int getid()
{
return id;
}
Item(string _name, int _id)
{
name = _name;
id = _id;
writename();
}
};
void FindItem(int id)
{
/* This takes the parameter and uses a loop to look through
all of the Item class objects. But how...? */
}
int main()
{
Item * rock = new Item("Rock", ITEM_ROCK);
Item * stone = new Item("Stone", ITEM_STONE);
int itemid = rock->getid();
FindItem(itemid);
system("PAUSE");
return 0;
}
I want to, like the comment says, use an id as a parameter for a function that can look through all of the class's objects in search of the given id. I just don't know how that can be done.
P.S: I don't want to use an array of class objects. They suck.
You need an array or a container class that contains a bunch of these objects. Then you can iterate through the objects and find the one you are looking for.
1 2 3 4 5 6 7 8 9 10 11
Item* array[2];
array[0] = new Item("Rock", ITEM_ROCK);
array[1] = new Item("Stone", ITEM_STONE);
for (int i = 0; i < 2; i++)
{
if (array[i]->getId == ITEM_ROCK)
{
array[i]->writename();
}
}