// file: uml1.cc // author: keller // RCS: $Id: uml1.cc,v 1.1 2000/02/07 20:22:23 keller Exp $ // // purpose: modeling the following UML class diagram // // .---------------. .---------------. // . Building .<*>----------. Room . // .---------------. * .---------------. // . . . number . // . . . length . // . . . width . // .---------------. .---------------. // . addRoom() . . . // .---------------. .---------------. // // where <*> is supposed to be a filled-in diamond (composition> // // Note: For purposes of exposition and conciseness, we do not use separate // header files, etc., nor do we include all constructors, destructors, // and assignment operators. #include // the STL list template class Building; // forward declaration /////////////////////////////////////////////////////////////////////////////// // A Room is in a Building. // It has a number, length, and width. // It knows its building. /////////////////////////////////////////////////////////////////////////////// class Room { private: Building *building; // the building containing this room int number; // the room number of this room int length; // the length of the room in feet int width; // the width of the room in feet public: // create a room in a building Room(Building *building, int number, int length, int width) { this->building = building; this->number = number; this->length = length; this->width = width; } // print a description of the room void show(ostream &out) { out << "room " << number << " " << length << "x" << width << endl; } }; /////////////////////////////////////////////////////////////////////////////// // A Building has a set of rooms. // Each is on a particular floor. /////////////////////////////////////////////////////////////////////////////// class Building { private: list rooms; // list of pointers to Room public: // create a Building Building() { } // add a new room to the building void addRoom(int number, int floor, int length, int width) { Room *theNewRoom = new Room(this, number, length, width); rooms.push_back(theNewRoom); } // show the contents of the building void show(ostream &out) { list::iterator p; for( p = rooms.begin(); p != rooms.end(); ++p ) { (*p)->show(out); } } }; // test program // create a building, add some rooms, and show the contents main() { Building b; b.addRoom(101, 1, 10, 20); b.addRoom(102, 1, 15, 30); b.addRoom(201, 2, 20, 25); b.addRoom(301, 3, 30, 50); b.show(cout); } /* output: room 101 10x20 room 102 15x30 room 201 20x25 room 301 30x50 */