#if ! defined(_CREATURE_H_) #define _CREATURE_H_ #include #define MAXNAME 20 class creature { private: static int count; char name[MAXNAME]; public: const int id; creature(char const * nm); ~creature(void); creature(creature const & src); creature marry(creature const & b); friend ostream & operator <<(ostream & os, creature const & x); }; #endif //#include "creature.h" #include int creature::count(0); creature::creature(char const *nm) : id(++count) { strncpy(name, nm, sizeof(name)-1); cout << *this << " is born\n"; } creature::~creature(void) { cout << *this << " is gone.\n"; } creature::creature(creature const & src) : id(++count) { strncpy(name, src.name, sizeof(name)-1); cout << *this << " is a copy of " << src << "\n"; } ostream & operator <<(ostream & os, creature const & x) { return os << x.name << '(' << x.id << ')'; } #include creature creature::marry(creature const & b) { int i; char tmp[MAXNAME]; for (i=0; name[i] && b.name[i]; ++i) tmp[i] = random() > RAND_MAX/2 ? name[i] : b.name[i]; tmp[i] = '\0'; return creature(tmp); } #if defined(TEST) #include int main(int argc, char *argv[]) { assert(3 <= argc >= 3 && 4 >= argc); if (4 <= argc) srandom(atoi(argv[3])); creature lambda(argv[1]); creature alpha(argv[2]), beta(lambda); cout << alpha.marry(beta) << " rules the world!\n"; } #endif /* a.out "windows" " intel" 30 windows(1) is born intel(2) is born windows(3) is a copy of windows(1) wintel(4) is born wintel(4) rules the world! wintel(4) is gone. windows(3) is gone. intel(2) is gone. windows(1) is gone. */ /* Exercises: 1. Separate the code into 3 files, write a makefile, and make. 2. What if '&' is removed from the parameter to the copy constructor? 3. What if '&' is removed from the parameter to creature::marry()? 4. What if creature::marry() takes a pointer as a parameter? 5. What if a 4-th creature delta is copied from the return value of alpha.marry(beta), and we use delta in the cout statement instead? 6. Modify creature::marry() so that it produces an offsping whose name is of the same length as the longer of the two parents. */