Download PROGRAMMING FUNDAMENTALS IN C++
Transcript
165
void Elevator::request(int newfloor)
{
if (newfloor < 1 || newfloor > MAXFLOOR || newfloor == currentFloor)
; // doing nothing
else if (newfloor > currentFloor) // move elevator up
{
cout \nStarting at floor currentFloor endl;
while (newfloor > currentFloor)
{
currentFloor++;
cout Going up now at floor currentFloor endl;
}
cout Stopping at floor currentFloor endl;
}
else // move elevator down
{
cout \nStarting at floor currentFloor endl;
while (newfloor < currentFloor)
{
currentFloor;
cout Going down now at floor currentFloor endl;
}
cout Stopping at floor currentFloor endl;
}
return;
}
The constructor function is straightforward. When an Elevator object is declared, it is initialized to the
oor specied; if no oor is explicitly given, the default value of 1 is used. For example, the declaration
Elevator a(7);
Initializes the variable a.currentFloor to 7, whereas the declaration
Elevator a;
uses the default argument value and initializes the variable a.currentFloor to 1.
The request() function dened in the implementation section is more complicated and provides the class's
primary service. Essentially, this function consists of an if-else statement having three parts: If an incorrect
service is requested, no action is taken; if a oor above the current position is selected, the elevator is moved
up; and if a oor below the current position is selected, the elevator is moved down. For movement up or
down, the function uses a while loop to increment or decrement the position one oor at a time and report
the elevator's movement using a cout statement.
program.
#include <iostream.h>
const int MAXFLOOR = 15;
//class declaration
class Elevator
{
private:
int currentFloor;
public:
Elevator(int = 1); //constructor
void request(int);
};
The following program includes this class in a working