 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 7 Outline 7.1 Introduction 7.2 Overview of Simulation Implementation.

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
CS-2303 System Programming Concepts
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
1 Object Oriented Analysis and Design. 2 Object-Oriented Analysis  Statement of what our client wants Object-Oriented Design  How to provide it using.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
1 Object-Oriented Programming Using C++ CLASS 27.
Templates Zhen Jiang West Chester University
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 5 Outline 5.1 Introduction 5.2 Collaborations 5.3 Creating Collaborations.
 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 4 Outline 4.1 Introduction 4.2 Class Operations 4.3 Creating Class.
 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 3 Outline 3.1 Introduction 3.2 Class Attributes 3.3 Statechart Diagrams.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
 2002 Prentice Hall, Inc. All rights reserved. Appendix H – Elevator Model Outline H.1 Introduction H.2 Class ElevatorModel H.3Classes Location and Floor.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 2 Outline 2.1 Introduction 2.2 Thinking About Objects: Identifying.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
2Object-Oriented Program Development Using C++ 3 Basic Loop Structures Loops repeat execution of an instruction set Three repetition structures: while,
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
Review the following : Flowcharting Variable declarations Output Input Arithmetic Calculations Conditional Statements Loops.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
 2003 Prentice Hall, Inc. All rights reserved. Appendix E – Elevator Model Outline E.1 Introduction E.2 Class ElevatorSimulation E.3Classes Location and.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 23 November 19, 2009.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
 2006 Doan Van Ban, IOIT. All rights reserved. 1 Case Study: E levator System Simulation Program Goal –Software simulator application –N-floor elevator.
 for loop  while loop  do-while loop for (begin point; end point ; incrementation ) { //statements to be repeated }
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
11 Introduction to Object Oriented Programming (Continued) Cats.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 2 September 3, 2009.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7: Classes Part II Outline 7.1 Introduction 7.2 const (Constant) Objects and const Member Functions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 6 Outline 6.1 Introduction 6.2 Implementation: Visibility 6.3 Implementation:
Functions and Libraries. Reference parameters void setToZero(int var) { var = 0; } int main() { int var = 0; setToZero(var); cout
1 Object-Oriented Programming Using C++ CLASS 2 Honors.
1 Class 19 Chapter 13 – Creating a class definition.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Chapter 1.2 Introduction to C++ Programming
Chapter 22 - C++ Templates
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Optional Case Study - Chapter 4
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Classes.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 4 - Control Structures: Part 1
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 22 - C++ Templates
Chapter 22 - C++ Templates
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

 2000 Deitel & Associates, Inc. All rights reserved. Optional Case Study - Chapter 7 Outline 7.1 Introduction 7.2 Overview of Simulation Implementation 7.3 Elevator Simulation Implementation Code (hyperlinked) a Driver Building Clock Scheduler Bell Light Door ElevatorButton FloorButton Elevator Floor Person Sample Simulation 7.4 Conclusion

 2000 Deitel & Associates, Inc. All rights reserved. 7.1 Introduction Chapter –Designed simulator Chapter 6 –Began programming simulator Body of Chapter 7 –Discussed dynamic object management ( new and delete ) –Composition - create classes with objects of other classes as data members –static and const class members

 2000 Deitel & Associates, Inc. All rights reserved. 7.2 Overview of Simulation Implementation Simulation controlled by a Building object –Contains two Floor objects, and an object of classes Elevator, Clock, and Scheduler Clock keeps track of time, incremented by the building every second Scheduler schedules arrival of people to each floor After each clock tick –Building updates scheduler with current time ( processTime ) Scheduler compares this with next arrival time for people on floor –If a person scheduled to arrive Scheduler checks if floor occupied ( isOccupied of class Floor ) If true, scheduler calls delayArrival to delay arrival time by second

 2000 Deitel & Associates, Inc. All rights reserved. 7.2 Overview of Simulation Implementation (II) If floor empty –Scheduler creates a Person object on appropriate floor –Person invokes pressButton (class FloorButton ) Floor button invokes summonElevator (class Elevator ) Elevator –Building updates elevator with time after each clock tick –Upon getting time, elevator checks state ("moving" or "not moving") –If moving, but not scheduled to arrive Elevator outputs direction of motion –If moving, and time matches arrival time Elevator stops, resets its button, rings bell Notifies floor it has arrived ( elevatorArrived, class Floor ) Floor resets floor button, turns on light Elevator opens door, passenger exits, new can person enter Elevator closes door, determines whether to move to other floor

 2000 Deitel & Associates, Inc. All rights reserved. 7.2 Overview of Simulation Implementation (III) Elevator (continued) –If elevator not moving when gets updated time Determines which floors need service –If current floor Rings bell, notifies floor it has arrived, and opens door Person on floor enters, presses button to start elevator moving to other floor –If other floor Elevator begins moving to that floor

 2000 Deitel & Associates, Inc. All rights reserved. 7.3 Elevator Simulation Implementation In previous sections –Gathered information about our system –Created object-oriented design of elevator simulation –Represented design using UML –We have discussed all the C++ needed to implement the simulation Remainder of section –Detailed walkthrough of implementation

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Driver for Simulation Prompt user for duration Ignore return character from input stream Create object, invoke member function Print messages when simulation begins and ends 1// Figure // Driver for the simulation. 3#include 4 5using std::cout; 6using std::cin; 7using std::endl; 8 9#include "building.h" 10 11int main() 12{ 13 int duration; // length of simulation in seconds cout << "Enter run time: "; 16 cin >> duration; 17 cin.ignore(); // ignore return char Building building; // create the building cout << endl << "*** ELEVATOR SIMULATION BEGINS ***" 22 << endl << endl; 23 building.runSimulation( duration ); // start simulation 24 cout << "*** ELEVATOR SIMULATION ENDS ***" << endl; return 0; 27}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Building Header Load headers of objects in class Floor, Elevator, Clock, and Scheduler objects 28// building.h 29// Definition for class Building. 30#ifndef BUILDING_H 31#define BUILDING_H 32 33#include "elevator.h" 34#include "floor.h" 35#include "clock.h" 36#include "scheduler.h" 37 38class Building { 39 40public: 41 Building(); // constructor 42 ~Building(); // destructor 43 void runSimulation( int ); // run sim for specified time 44 45private: 46 Floor floor1; // floor1 object 47 Floor floor2; // floor2 object 48 Elevator elevator; // elevator object 49 Clock clock; // clock object 50 Scheduler scheduler; // scheduler object 51}; 52 53#endif // BUILDING_H

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Building Implementation FLOOR1 and FLOOR2 are constants, defined in class Floor Constructors for objects of Building called with appropriate arguments Loop until specified time has passed. cin.get() : stops text from scrolling; when user presses key, it resumes 54// building.cpp 55// Member function definitions for class Building. 56#include 57 58using std::cout; 59using std::cin; 60using std::endl; 61 62#include "building.h" 63 64Building::Building() // constructor 65 : floor1( Floor::FLOOR1, elevator ), 66 floor2( Floor::FLOOR2, elevator ), 67 elevator( floor1, floor2 ), 68 scheduler( floor1, floor2 ) 69{ cout << "building created" << endl; } 70 71Building::~Building() // destructor 72{ cout << "building destroyed" << endl; } 73 74// control the simulation 75void Building::runSimulation( int totalTime ) 76{ 77 int currentTime = 0; while ( currentTime < totalTime ) { 80 clock.tick(); 81 currentTime = clock.getTime(); 82 cout << "TIME: " << currentTime << endl; 83 scheduler.processTime( currentTime ); 84 elevator.processTime( currentTime ); 85 cin.get(); // stop each second for user to view output 86 } 87}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Clock Header Simple class, composed of no other objects Increments time through tick Current time available through getTime Note that getTime is const 88// clock.h 89// Definition for class Clock. 90#ifndef CLOCK_H 91#define CLOCK_H 92 93class Clock { 94 95public: 96 Clock(); // constructor 97 ~Clock(); // destructor 98 void tick(); // increment clock by one second 99 int getTime() const; // returns clock's current time private: 102 int time; // clock's time 103}; #endif // CLOCK_H

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Clock Implementation Function definitions 106// clock.cpp 107// Member function definitions for class Clock. 108#include using std::cout; 111using std::endl; #include "clock.h" Clock::Clock() // constructor 116 : time( 0 ) 117{ cout << "clock created" << endl; } Clock::~Clock() // destructor 120{ cout << "clock destroyed" << endl; } void Clock::tick() // increment time by 1 123{ time++; } int Clock::getTime() const // return current time 126{ return time; }

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Scheduler Header processTime operation Private utility functions (discussed in implementation file) 127// scheduler.h 128// definition for class Scheduler 129#ifndef SCHEDULER_H 130#define SCHEDULER_H class Floor; // forward declaration class Scheduler { public: 137 Scheduler( Floor &, Floor & ); // constructor 138 ~Scheduler(); // destructor 139 void processTime( int ); // set scheduler's time private: 142 // schedule arrival to a floor 143 void scheduleTime( const Floor & ); // delay arrival to a floor 146 void delayTime( const Floor & ); // create new person; place on floor 149 void createNewPerson( Floor & ); // handle person arrival on a floor 152 void handleArrivals( Floor &, int );

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Scheduler Header Member variables int currentClockTime; Floor &floor1Ref; 157 Floor &floor2Ref; int floor1ArrivalTime; 160 int floor2ArrivalTime; 161}; #endif // SCHEDULER_H

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Scheduler Implementation Constructor : seeds pseudo-random arrival time Calls scheduleTime for each floor Destructor 164// scheduler.cpp 165// Member function definitions for class Scheduler. 166#include using std::cout; 169using std::endl; #include 172#include #include "scheduler.h" 175#include "floor.h" 176#include "person.h" // constructor 179Scheduler::Scheduler( Floor &firstFloor, Floor &secondFloor ) 180 : currentClockTime( 0 ), floor1Ref( firstFloor ), 181 floor2Ref( secondFloor ) 182{ 183 srand( time( 0 ) ); // seed random number generator 184 cout << "scheduler created" << endl; // schedule first arrivals for floor 1 and floor scheduleTime( floor1Ref ); 188 scheduleTime( floor2Ref ); 189} Scheduler::~Scheduler() // destructor 192{ cout << "scheduler destroyed" << endl; } 193

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Scheduler Implementation scheduleTime : creates pseudorandom arrival time for Person objects on each floor delayTime : delays arrival time for one second 194// schedule arrival on a floor 195void Scheduler::scheduleTime( const Floor &floor ) 196{ 197 int floorNumber = floor.getNumber(); 198 int arrivalTime = currentClockTime + ( 5 + rand() % 16 ); floorNumber == Floor::FLOOR1 ? 201 floor1ArrivalTime = arrivalTime : 202 floor2ArrivalTime = arrivalTime; cout << "(scheduler schedules next person for floor " 205 << floorNumber << " at time " << arrivalTime << ')' 206 << endl; 207} // reschedule an arrival on a floor 210void Scheduler::delayTime( const Floor &floor ) 211{ 212 int floorNumber = floor.getNumber(); int arrivalTime = ( floorNumber == Floor::FLOOR1 ) ? floor1ArrivalTime : ++floor2ArrivalTime; cout << "(scheduler delays next person for floor " 218 << floorNumber << " until time " << arrivalTime << ')' 219 << endl; 220} 221

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Scheduler Implementation processTime: building updates scheduler 's time using this function Call handleArrivals for each floor createNewPerson: Creates new object of class Person Sends stepOntoFloor message scheduleTime: Calculate arrival time 222// give time to scheduler 223void Scheduler::processTime( int time ) 224{ 225 currentClockTime = time; // record time // handle arrivals on floor handleArrivals( floor1Ref, currentClockTime ); // handle arrivals on floor handleArrivals( floor2Ref, currentClockTime ); 232} // create new person and place it on specified floor 235void Scheduler::createNewPerson( Floor &floor ) 236{ 237 int destinationFloor = 238 floor.getNumber() == Floor::FLOOR1 ? 239 Floor::FLOOR2 : Floor::FLOOR1; // create new person 242 Person *newPersonPtr = new Person( destinationFloor ); cout << "scheduler creates person " 245 getID() << endl; // place person on proper floor 248 newPersonPtr->stepOntoFloor( floor ); scheduleTime( floor ); // schedule next arrival 251}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Scheduler Implementation handleArrivals: Compares current time to arrivalTime If times match and floor occupied, delay arrival by one second If unoccupied, create a new person on that floor // handle arrivals for a specified floor 254void Scheduler::handleArrivals( Floor &floor, int time ) 255{ 256 int floorNumber = floor.getNumber(); int arrivalTime = ( floorNumber == Floor::FLOOR1 ) ? 259 floor1ArrivalTime : floor2ArrivalTime; if ( arrivalTime == time ) { if ( floor.isOccupied() ) // see if floor occupied 264 delayTime( floor ); 265 else 266 createNewPerson( floor ); 267 } 268}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Bell Header Contains no other objects 269// bell.h 270// Definition for class Bell. 271#ifndef BELL_H 272#define BELL_H class Bell { public: 277 Bell(); // constructor 278 ~Bell(); // destructor 279 void ringBell() const; // ring the bell 280}; #endif // BELL_H

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Bell Implementation Constructor Destructor ringBell 283// bell.cpp 284// Member function definitions for class Bell. 285#include using std::cout; 288using std::endl; #include "bell.h" Bell::Bell() // constructor 293{ cout << "bell created" << endl; } Bell::~Bell() // destructor 296{ cout << "bell destroyed" << endl; } void Bell::ringBell() const // ring bell 299{ cout << "elevator rings its bell" << endl; }

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Light Header Member functions Member variables 300// light.h 301// Definition for class Light. 302#ifndef LIGHT_H 303#define LIGHT_H class Light { public: 308 Light( const char * ); // constructor 309 ~Light(); // destructor 310 void turnOn(); // turns light on 311 void turnOff(); // turns light off private: 314 bool on; // true if on; false if off 315 const char *name; // which floor the light is on 316}; #endif // LIGHT_H

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Light Implementation Constructor Destructor turnOn: sets on to true turnOff: sets on to false 319// light.cpp 320// Member function definitions for class Light. 321#include using std::cout; 324using std::endl; #include "light.h" Light::Light( const char *string ) // constructor 329 : on( false ), name( string ) 330{ cout << name << " light created" << endl; } Light::~Light() // destructor 333{ cout << name << " light destroyed" << endl; } void Light::turnOn() // turn light on 336{ 337 on = true; 338 cout << name << " turns on its light" << endl; 339} void Light::turnOff() // turn light off 342{ 343 on = false; 344 cout << name << " turns off its light" << endl; 345}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Door Header In our simulation, door signals passenger to exit elevator, and new person to enter 346// door.h 347// Definition for class Door. 348#ifndef DOOR_H 349#define DOOR_H class Person; // forward declaration 352class Floor; // forward declaration 353class Elevator; // forward declaration class Door { public: 358 Door(); // constructor 359 ~Door(); // destructor void openDoor( Person * const, Person * const, 362 Floor &, Elevator & ); 363 void closeDoor( const Floor & ); private: 366 bool open; // open or closed 367}; #endif // DOOR_H Door is a composite object in class Elevator ; header for Elevator must contain #include "door.h" Door has a reference to an Elevator object- could put #include "elevator.h" in Door 's header. Causes circular include problem. Avoid this by using forward class declarations (line 353 ) - tells compiler definition of class lies outside of file.

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Door Implementation Load headers - correspond to forward declarations Header files have required function prototypes Constructor Destructor 370// door.cpp 371// Member function definitions for class Door. 372#include using std::cout; 375using std::endl; #include "door.h" 378#include "person.h" 379#include "floor.h" 380#include "elevator.h" Door::Door() // constructor 383 : open( false ) 384{ cout << "door created" << endl; } Door::~Door() // destructor 387{ cout << "door destroyed" << endl; } 388

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Door Implementation openDoor : Checks that door is not already open Checks pointer to see if passenger needs to exit - calls exitElevator Passenger leaves simulation Checks for new passenger - calls enterElevator closeDoor: Checks if Door open; if so, closes it 389// open the door 390void Door::openDoor( Person * const passengerPtr, 391 Person * const nextPassengerPtr, 392 Floor &currentFloor, Elevator &elevator ) 393{ 394 if ( !open ) { 395 open = true; cout << "elevator opens its door on floor " 398 << currentFloor.getNumber() << endl; if ( passengerPtr != 0 ) { 401 passengerPtr->exitElevator( currentFloor, elevator ); 402 delete passengerPtr; // passenger leaves simulation 403 } if ( nextPassengerPtr != 0 ) 406 nextPassengerPtr->enterElevator( 407 elevator, currentFloor ); 408 } 409} // close the door 412void Door::closeDoor( const Floor &currentFloor ) 413{ 414 if ( open ) { 415 open = false; 416 cout << "elevator closes its door on floor " 417 << currentFloor.getNumber() << endl; 418 } 419}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline ElevatorButton Header Public operations Member variables 420// elevatorButton.h 421// Definition for class ElevatorButton. 422#ifndef ELEVATORBUTTON_H 423#define ELEVATORBUTTON_H class Elevator; // forward declaration class ElevatorButton { public: 430 ElevatorButton( Elevator & ); // constructor 431 ~ElevatorButton(); // destructor void pressButton(); // press the button 434 void resetButton(); // reset the button private: 437 bool pressed; // state of button 438 Elevator &elevatorRef; // reference to button's elevator 439}; #endif // ELEVATORBUTTON_H

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline ElevatorButton Implementation pressButton: Sets pressed to true Sends prepareToLeave message to elevator resetButton: sets pressed to false 442// elevatorButton.cpp: 443// Member function definitions for class ElevatorButton. 444#include using std::cout; 447using std::endl; #include "elevatorButton.h" 450#include "elevator.h" // constructor 453ElevatorButton::ElevatorButton( Elevator &elevatorHandle ) 454 : pressed( false ), elevatorRef( elevatorHandle ) 455{ cout << "elevator button created" << endl; } ElevatorButton::~ElevatorButton() // destructor 458{ cout << "elevator button destroyed" << endl; } void ElevatorButton::pressButton() // press the button 461{ 462 pressed = true; 463 cout << "elevator button tells elevator to prepare to leave" 464 << endl; 465 elevatorRef.prepareToLeave( true ); 466} void ElevatorButton::resetButton() // reset the button 469{ pressed = false; }

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline FloorButton Header Same member functions as ElevatorButton Member variables 470// floorButton.h 471// Definition for class FloorButton. 472#ifndef FLOORBUTTON_H 473#define FLOORBUTTON_H class Elevator; // forward declaration class FloorButton { public: 480 FloorButton( const int, Elevator & ); // constructor 481 ~FloorButton(); // destructor void pressButton(); // press the button 484 void resetButton(); // reset the button private: 487 const int floorNumber; // number of the button's floor 488 bool pressed; // state of button // reference to button's elevator 491 Elevator &elevatorRef; 492}; #endif // FLOORBUTTON_H

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline FloorButton Implementation Constructor Destructor 495// floorButton.cpp 496// Member function definitions for class FloorButton. 497#include using std::cout; 500using std::endl; #include "floorButton.h" 503#include "elevator.h" // constructor 506FloorButton::FloorButton( const int number, 507 Elevator &elevatorHandle ) 508 : floorNumber( number ), pressed( false ), 509 elevatorRef( elevatorHandle ) 510{ 511 cout << "floor " << floorNumber << " button created" 512 << endl; 513} FloorButton::~FloorButton() // destructor 516{ 517 cout << "floor " << floorNumber << " button destroyed" 518 << endl; 519} 520

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline FloorButton Implementation pressButton : Set pressed to true, call summonElevator resetButton: Set pressed to false 521// press the button 522void FloorButton::pressButton() 523{ 524 pressed = true; 525 cout << "floor " << floorNumber 526 << " button summons elevator" << endl; 527 elevatorRef.summonElevator( floorNumber ); 528} // reset the button 531void FloorButton::resetButton() 532{ pressed = false; }

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Elevator Header Load headers and forward declarations public member functions 533// elevator.h 534// Definition for class Elevator. 535#ifndef ELEVATOR_H 536#define ELEVATOR_H #include "elevatorButton.h" 539#include "door.h" 540#include "bell.h" class Floor; // forward declaration 543class Person; // forward declaration class Elevator { public: 548 Elevator( Floor &, Floor & ); // constructor 549 ~Elevator(); // destructor 550 void summonElevator( int ); // request to service a floor 551 void prepareToLeave( bool ); // prepare to leave 552 void processTime( int ); // give time to elevator 553 void passengerEnters( Person * const ); // board a passenger 554 void passengerExits(); // exit a passenger 555 ElevatorButton elevatorButton; // note public object 556 elevatorButton public so all Person objects can use it.

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Elevator Header private utility functions static const data members available to all objects of class Elevator Data members and handles Need pointer (not reference) for Person object because passenger changes 557private: 558 void processPossibleArrival(); 559 void processPossibleDeparture(); 560 void arriveAtFloor( Floor & ); 561 void move(); // time to move between floors 564 static const int ELEVATOR_TRAVEL_TIME; 565 static const int UP; // UP direction 566 static const int DOWN; // DOWN direction int currentBuildingClockTime; // current time 569 bool moving; // elevator state 570 int direction; // current direction 571 int currentFloor; // current location 572 int arrivalTime; // time to arrive at a floor 573 bool floor1NeedsService; // floor1 service flag 574 bool floor2NeedsService; // floor2 service flag Floor &floor1Ref; // reference to floor1 577 Floor &floor2Ref; // reference to floor2 578 Person *passengerPtr; // pointer to current passenger Door door; // door object 581 Bell bell; // bell object 582}; #endif // ELEVATOR_H bell and door are private because people do not usually interface with those objects.

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Elevator Implementation Constructor (note large member- initializer list) Destructor 585// elevator.cpp 586// Member function definitions for class Elevator. 587#include using std::cout; 590using std::endl; #include "elevator.h" 593#include "person.h" 594#include "floor.h" const int Elevator::ELEVATOR_TRAVEL_TIME = 5; 597const int Elevator::UP = 0; 598const int Elevator::DOWN = 1; // constructor 601Elevator::Elevator( Floor &firstFloor, Floor &secondFloor ) 602 : elevatorButton( *this ), currentBuildingClockTime( 0 ), 603 moving( false ), direction( UP ), 604 currentFloor( Floor::FLOOR1 ), arrivalTime( 0 ), 605 floor1NeedsService( false ), floor2NeedsService( false ), 606 floor1Ref( firstFloor ), floor2Ref( secondFloor ), 607 passengerPtr( 0 ) 608{ cout << "elevator created" << endl; } Elevator::~Elevator() // destructor 611{ cout << "elevator destroyed" << endl; } 612

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Elevator Implementation processTime: Updates time (called by building ) Check possible departure or arrival and determine if elevator moving or not processPossible Arrival: Compare time to arrival time If match, update floor, direction, call arriveAtFloor 613// give time to elevator 614void Elevator::processTime( int time ) 615{ 616 currentBuildingClockTime = time; if ( moving ) 619 processPossibleArrival(); 620 else 621 processPossibleDeparture(); if ( !moving ) 624 cout << "elevator at rest on floor " 625 << currentFloor << endl; 626} // when elevator is moving, determine if it should stop 629void Elevator::processPossibleArrival() 630{ 631 // if elevator arrives at destination floor 632 if ( currentBuildingClockTime == arrivalTime ) { currentFloor = // update current floor 635 ( currentFloor == Floor::FLOOR1 ? 636 Floor::FLOOR2 : Floor::FLOOR1 ); direction = // update direction 639 ( currentFloor == Floor::FLOOR1 ? UP : DOWN ); cout << "elevator arrives on floor " 642 << currentFloor << endl; arriveAtFloor( currentFloor == Floor::FLOOR1 ? 645 floor1Ref : floor2Ref );

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Elevator Implementation processPossible Arrival (cont'd) : Exit function (if times match) If times do not match, print message processPossible Departure: If needs to service current floor, call arriveAtFloor If needs to service other floor, call prepareToLeave (which will leave if argument true ) return; 648 } // elevator is moving 651 cout << "elevator moving " 652 << ( direction == UP ? "up" : "down" ) << endl; 653} // determine if elevator should move 656void Elevator::processPossibleDeparture() 657{ 658 // this floor needs service? 659 bool currentFloorNeedsService = 660 currentFloor == Floor::FLOOR1 ? 661 floor1NeedsService : floor2NeedsService; // other floor needs service? 664 bool otherFloorNeedsService = 665 currentFloor == Floor::FLOOR1 ? 666 floor2NeedsService : floor1NeedsService; // service this floor (if needed) 669 if ( currentFloorNeedsService ) { 670 arriveAtFloor( currentFloor == Floor::FLOOR1 ? 671 floor1Ref : floor2Ref ); return; 674 } // service other floor (if needed) 677 else prepareToLeave( otherFloorNeedsService ); 678} 679

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Elevator Implementation arriveAtFloor: Stops elevator Resets button, rings bell elevatorArrived returns pointer to Person object waiting on floor Open door Check if floors need service If not, reset service flags 680// arrive at a particular floor 681void Elevator::arriveAtFloor( Floor& arrivalFloor ) 682{ 683 moving = false; // reset state cout << "elevator resets its button" << endl; 686 elevatorButton.resetButton(); bell.ringBell(); // notify floor that elevator has arrived 691 Person *floorPersonPtr = arrivalFloor.elevatorArrived(); door.openDoor( passengerPtr, floorPersonPtr, 694 arrivalFloor, *this ); // this floor needs service? 697 bool currentFloorNeedsService = 698 currentFloor == Floor::FLOOR1 ? 699 floor1NeedsService : floor2NeedsService; // other floor needs service? 702 bool otherFloorNeedsService = 703 currentFloor == Floor::FLOOR1 ? 704 floor2NeedsService : floor1NeedsService; // if this floor does not need service 707 // prepare to leave for the other floor 708 if ( !currentFloorNeedsService ) 709 prepareToLeave( otherFloorNeedsService ); 710 else // otherwise, reset service flag 711 currentFloor == Floor::FLOOR1 ? 712 floor1NeedsService = false: floor2NeedsService = false; 713}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Elevator Implementation summonElevator: Allows other objects to request service, sets service flag passengerEnters: Update passengerPtr handle passengerExits: Set passengerPtr handle to zero (no passenger) // request service from elevator 716void Elevator::summonElevator( int floor ) 717{ 718 // set appropriate servicing flag 719 floor == Floor::FLOOR1 ? 720 floor1NeedsService = true : floor2NeedsService = true; 721} // accept a passenger 724void Elevator::passengerEnters( Person * const personPtr ) 725{ 726 // board passenger 727 passengerPtr = personPtr; cout getID() 730 << " enters elevator from floor " 731 << currentFloor << endl; 732} // notify elevator that passenger is exiting 735void Elevator::passengerExits() { passengerPtr = 0; } 736

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Elevator Implementation prepareToLeave: Elevator notifies floor it may leave, closes door Elevator decides if it must leave move: Set moving to true Schedule arrival time Print message 737// prepare to leave a floor 738void Elevator::prepareToLeave( bool leaving ) 739{ 740 Floor &thisFloor = 741 currentFloor == Floor::FLOOR1 ? floor1Ref : floor2Ref; // notify floor that elevator may be leaving 744 thisFloor.elevatorLeaving(); door.closeDoor( thisFloor ); if ( leaving ) // leave, if necessary 749 move(); 750} void Elevator::move() // go to a particular floor 753{ 754 moving = true; // change state // schedule arrival time 757 arrivalTime = currentBuildingClockTime ELEVATOR_TRAVEL_TIME; cout << "elevator begins moving " 761 << ( direction == DOWN ? "down " : "up ") 762 << "to floor " 763 << ( direction == DOWN ? '1' : '2' ) 764 << " (arrives at time " << arrivalTime << ')' 765 << endl; 766}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Floor Header Member functions 767// floor.h 768// Definition for class Floor. 769#ifndef FLOOR_H 770#define FLOOR_H #include "floorButton.h" 773#include "light.h" class Elevator; // forward declaration 776class Person; // forward declaration class Floor { public: 781 Floor( int, Elevator & ); // constructor 782 ~Floor(); // destructor 783 bool isOccupied() const; // return true if floor occupied 784 int getNumber() const; // return floor's number // pass a handle to new person coming on floor 787 void personArrives( Person * const ); // notify floor that elevator has arrived 790 Person *elevatorArrived(); // notify floor that elevator is leaving 793 void elevatorLeaving(); // notify floor that person is leaving floor 796 void personBoardingElevator();

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Floor Header public const members, initialized in implementation private data member Reference to Elevator object (does not change over time) Pointer to Person object (occupant changes over time) static const int FLOOR1; 799 static const int FLOOR2; 800 FloorButton floorButton; // floorButton object private: 803 const int floorNumber; // the floor's number 804 Elevator &elevatorRef; // pointer to elevator 805 Person *occupantPtr; // pointer to person on floor 806 Light light; // light object 807}; #endif // FLOOR_H floorButton is public so all Person objects can interface with it. Light is private, because people do not interface with it.

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Floor Implementation Constructor Destructor isOccupied: Returns true if occupantPtr not 0 810// floor.cpp 811// Member function definitions for class Floor. 812#include using std::cout; 815using std::endl; #include "floor.h" 818#include "person.h" 819#include "elevator.h" const int Floor::FLOOR1 = 1; 822const int Floor::FLOOR2 = 2; // constructor 825Floor::Floor(int number, Elevator &elevatorHandle ) 826 : floorButton( number, elevatorHandle ), 827 floorNumber( number ), elevatorRef( elevatorHandle ), 828 occupantPtr ( 0 ), 829 light( floorNumber == 1 ? "floor 1" : "floor 2" ) 830{ cout << "floor " << floorNumber << " created" << endl; } // destructor 833Floor::~Floor() 834{ cout << "floor " << floorNumber << " destroyed" << endl; } // determine if floor is occupied 837bool Floor::isOccupied() const 838{ return ( occupantPtr != 0 ); } 839

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Floor Implementation getNumber: Returns floorNumber personArrives: Set occupantPtr to point to new Person object elevatorArrived: Print message Reset button Turn on light Return pointer elevatorLeaving: Turn off light personBoarding Elevator: Set occupantPtr to 0 840// return this floor's number 841int Floor::getNumber() const { return floorNumber; } // pass person to floor 844void Floor::personArrives( Person * const personPtr ) 845{ occupantPtr = personPtr; } // notify floor that elevator has arrived 848Person *Floor::elevatorArrived() 849{ 850 // reset the button on floor, if necessary 851 cout << "floor " << floorNumber 852 << " resets its button" << endl; 853 floorButton.resetButton(); light.turnOn(); return occupantPtr; 858} // tell floor that the elevator is leaving 861void Floor::elevatorLeaving() { light.turnOff(); } // notifies floor that a person is leaving it 864void Floor::personBoardingElevator() { occupantPtr = 0; }

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Person Header Forward declarations, public member functions, private data 865// person.h 866// definition of class Person 867#ifndef PERSON_H 868#define PERSON_H class Floor; // forward declaration 871class Elevator; // forward declaration class Person { public: 876 Person( const int ); // constructor 877 ~Person(); // destructor 878 int getID() const; // returns person's ID void stepOntoFloor( Floor & ); 881 void enterElevator( Elevator &, Floor & ); 882 void exitElevator( const Floor &, Elevator & ) const; private: 885 static int personCount; // total number of persons 886 const int ID; // person's unique ID # 887 const int destinationFloor; // destination floor # 888}; #endif // PERSON_H

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Person Implementation Initialize personCount Constructor Destructor getID: Returns ID 891// person.cpp 892// Member function definitions for class Person. 893#include using std::cout; 896using std::endl; #include "person.h" 899#include "floor.h" 900#include "elevator.h" // initialize static member personCount 903int Person::personCount = 0; Person::Person( const int destFloor ) // constructor 906 : ID( ++personCount ), destinationFloor( destFloor ) 907{} Person::~Person() // destructor 910{ 911 cout << "person " << ID << " exits simulation on floor " 912 << destinationFloor << " (person destructor invoked)" 913 << endl; 914} int Person::getID() const { return ID; } // get the ID 917

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Person Implementation stepOntoFloor: Notify floor ( personArrives ) Summon elevator ( pressButton ) enterElevator: Notify floor ( personBoarding Elevator ) Enter elevator Press button 918// person walks onto a floor 919void Person::stepOntoFloor( Floor& floor ) 920{ 921 // notify floor a person is coming 922 cout << "person " << ID << " steps onto floor " 923 << floor.getNumber() << endl; 924 floor.personArrives( this ); // press button on the floor 927 cout << "person " << ID 928 << " presses floor button on floor " 929 << floor.getNumber() << endl; 930 floor.floorButton.pressButton(); 931} // person enters elevator 934void Person::enterElevator( Elevator &elevator, Floor &floor ) 935{ 936 floor.personBoardingElevator(); // person leaves floor elevator.passengerEnters( this ); // person enters elevator // press button on elevator 941 cout << "person " << ID 942 << " presses elevator button" << endl; 943 elevator.elevatorButton.pressButton(); 944}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Person Implementation exitElevator: Print message Send exit message ( passengerExits ) // person exits elevator 947void Person::exitElevator( 948 const Floor &floor, Elevator &elevator ) const 949{ 950 cout << "person " << ID << " exits elevator on floor " 951 << floor.getNumber() << endl; 952 elevator.passengerExits(); 953}

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Sample Simulation Enter run time: 30 (scheduler schedules next person for floor 1 at time 5) (scheduler schedules next person for floor 2 at time 17) *** ELEVATOR SIMULATION BEGINS *** TIME: 1 elevator at rest on floor 1 TIME: 2 elevator at rest on floor 1 TIME: 3 elevator at rest on floor 1 TIME: 4 elevator at rest on floor 1 TIME: 5 scheduler creates person 1 person 1 steps onto floor 1 person 1 presses floor button on floor 1 floor 1 button summons elevator (scheduler schedules next person for floor 1 at time 20) elevator resets its button elevator rings its bell floor 1 resets its button floor 1 turns on its light elevator opens its door on floor 1 person 1 enters elevator from floor 1 person 1 presses elevator button elevator button tells elevator to prepare to leave floor 1 turns off its light elevator closes its door on floor 1 elevator begins moving up to floor 2 (arrives at time 10)

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Sample Simulation TIME: 6 elevator moving up TIME: 7 elevator moving up TIME: 8 elevator moving up TIME: 9 elevator moving up TIME: 10 elevator arrives on floor 2 elevator resets its button elevator rings its bell floor 2 resets its button floor 2 turns on its light elevator opens its door on floor 2 person 1 exits elevator on floor 2 floor 2 turns off its light elevator closes its door on floor 2 elevator at rest on floor 2 TIME: 11 elevator at rest on floor 2 TIME: 12 elevator at rest on floor 2 TIME: 13 elevator at rest on floor 2

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Sample Simulation TIME: 14 elevator at rest on floor 2 TIME: 15 elevator at rest on floor 2 TIME: 16 elevator at rest on floor 2 TIME: 17 scheduler creates person 2 person 2 steps onto floor 2 person 2 presses floor button on floor 2 floor 2 button summons elevator (scheduler schedules next person for floor 2 at time 34) elevator resets its button elevator rings its bell floor 2 resets its button floor 2 turns on its light elevator opens its door on floor 2 person 2 enters elevator from floor 2 person 2 presses elevator button elevator button tells elevator to prepare to leave floor 2 turns off its light elevator closes its door on floor 2 elevator begins moving down to floor 1 (arrives at time 22) TIME: 18 elevator moving down TIME: 19 elevator moving down

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Sample Simulation TIME: 20 scheduler creates person 3 person 3 steps onto floor 1 person 3 presses floor button on floor 1 floor 1 button summons elevator (scheduler schedules next person for floor 1 at time 26) elevator moving down TIME: 21 elevator moving down TIME: 22 elevator arrives on floor 1 elevator resets its button elevator rings its bell floor 1 resets its button floor 1 turns on its light elevator opens its door on floor 1 person 2 exits elevator on floor 1 person 3 enters elevator from floor 1 person 3 presses elevator button elevator button tells elevator to prepare to leave floor 1 turns off its light elevator closes its door on floor 1 elevator begins moving up to floor 2 (arrives at time 27) TIME: 23 elevator moving up TIME: 24 elevator moving up TIME: 25 elevator moving up

 2000 Deitel & Associates, Inc. All rights reserved. Home Outline Sample Simulation TIME: 26 scheduler creates person 4 person 4 steps onto floor 1 person 4 presses floor button on floor 1 floor 1 button summons elevator (scheduler schedules next person for floor 1 at time 35) elevator moving up TIME: 27 elevator arrives on floor 2 elevator resets its button elevator rings its bell floor 2 resets its button floor 2 turns on its light elevator opens its door on floor 2 person 3 exits elevator on floor 2 floor 2 turns off its light elevator closes its door on floor 2 elevator begins moving down to floor 1 (arrives at time 32) TIME: 28 elevator moving down TIME: 29 elevator moving down TIME: 30 elevator moving down *** ELEVATOR SIMULATION ENDS ***

 2000 Deitel & Associates, Inc. All rights reserved. 7.4 Conclusion Congratulations! –We have made a working simulator Chapter 9 –Discuss inheritance and apply it to our elevator