c++ - simple class question.
- inter9988 yahoo.com (19/19) Mar 25 2006 the code :
- Bertel Brander (72/78) Mar 26 2006 I see two solutions:
the code : /* class creature { char name[20]; int strenght; char item[20][20]; }; main() { creature dog1; creature dog2; creature tiger; // i want to print all the creatures. cuz im making aruond 200 creatures. // is there anyway to printout or count all the creatures. // something like : for(i=0;i<MX_CREATURE;i++){ printCreatureState(); } } */ im new to c++. any idea ?
Mar 25 2006
inter9988 yahoo.com wrote:// i want to print all the creatures. cuz im making aruond 200 creatures. // is there anyway to printout or count all the creatures. // something like : for(i=0;i<MX_CREATURE;i++){ printCreatureState(); } im new to c++. any idea ?I see two solutions: 1: Let the user of the creatures (in your case main) create a list. 2: Let the creatures themself create the list. To do the latter: Have a list of pointers to creatures: std::list<creature *> CreatureList; Add constructors to the creature class: creature(); ~creature(); Let the constructor add itself to the list: creature::creature() { CreatureList.push_back(this); } And let the destructor remove it again: creature::~creature() { std::list<creature *>::iterator it = std::find(CreatureList.begin(), CreatureList.end(), this); if(it != CreatureList.end()) CreatureList.erase(it); else std::cout << "Ups, failed to find me in the list" << std::endl; } I made the following test program to test it: #include <iostream> #include <list> class creature { public: creature(); ~creature(); char name[20]; int strenght; char item[20][20]; }; std::list<creature *> CreatureList; creature::creature() { CreatureList.push_back(this); } creature::~creature() { std::list<creature *>::iterator it = std::find(CreatureList.begin(), CreatureList.end(), this); if(it != CreatureList.end()) CreatureList.erase(it); else std::cout << "Ups, failed to find me in the list" << std::endl; } std::ostream& operator << (std::ostream& os, const creature& cr) { os << cr.name; return os; } int main() { creature dog1; strcpy(dog1.name, "Dog1"); creature dog2; strcpy(dog2.name, "Dog2"); creature tiger; strcpy(tiger.name, "Tiger"); std::list<creature *>::iterator it; for(it = CreatureList.begin(); it != CreatureList.end(); ++it) std::cout << *(*it) << std::endl; } -- Absolutely not the best homepage on the net: http://home20.inet.tele.dk/midgaard But it's mine - Bertel
Mar 26 2006