Car.cpp
CarDemo.cpp
Car.h
/* Car.h - Specification file for the Car class. */
#ifndef CAR_H
#define CAR_H
#include <string>
using std::string;
class Car
{
private:
int yearModel; // Holding the car's year model
string make; // Holding the make of the car
int speed; // Holding the car's current speed
public:
// Constructor
Car(int, string);
// Mutators
void accelerate();
void brake();
// Accessors
int getyearModel() const // Returns the car's year model.
{ return yearModel; }
string getMake() const // Returns the make of the car.
{ return make; }
int getSpeed() const // Returns the car's current speed.
{ return speed; }
};
#endif
Car.cpp
/* Car.cpp - Implementation file for the Car class */
#include "Car.h"
/* **********************************************************
Car::Car
The constructor accepts arguments for yearModel and make.
0 is assigned to the speed member.
********************************************************** */
Car::Car(int mYear, string mMake)
{
yearModel = mYear;
make = mMake;
speed = 0;
}
/* **********************************************************
Car::accelerate
This function adds 10 to the speed member variable each
time it is called.
********************************************************** */
void Car::accelerate()
{
speed += 10;
}
/* **********************************************************
Car::brake
This function subtracts 10 from the speed member variable
each time it is called.
********************************************************** */
void Car::brake()
{
speed -= 10;
}
CarDemo.cpp
/* Car Demo - This function demonstrates the Car class. */
#include <iostream>
#include <iomanip>
#include "Car.h"
using std::cout;
using std::cin;
using std::setw;
int main()
{
Car cyberCar(1978, "Porsche 911 SC");
cout << "WELCOME TO TEST DRIVE XXII\n\n";
cout << "The cyber car you are going to drive is a "
<< cyberCar.getMake() << " built in " << cyberCar.getyearModel() << ".\n";
cout << "The engine is turned off, and your current speed is "
<< cyberCar.getSpeed() << " mp/h.\n\n";
// Demonstrating the accelerate function
cout << "You start the engine and your car accelerates:\n";
for (int accel = 0; accel < 5; accel++)
{
cyberCar.accelerate();
cout << "Your current speed is: " << setw(2) << cyberCar.getSpeed() << " mp/h\n";
}
// Demonstrating the brake function
cout << "\nYou hit the brake and your car starts slowing down:\n";
while(cyberCar.getSpeed() > 0)
{
cyberCar.brake();
cout << "Your current speed is: " << setw(2) << cyberCar.getSpeed() << " mp/h\n";
}
cout << "\nYour car has stopped, and you turn off the engine.";
cin.ignore();
cin.get();
return 0;
}
No comments:
Post a Comment