The concept of time makes a useful programming example because it's familiar and, in the problem's restricted context, consists of only a few discrete values. Chapter 4 used it to demonstrate structures, while Chapter 5 modified it to demonstrate three ways of passing structure arguments to functions. It appears throughout this chapter, demonstrating many object-oriented programming features. The final version unites the previous examples, presenting them as a complete single-class program highlighting the conversion from a structure to a class. The Time class example consists of three files: Time.h contains the class specification; Time.cpp contains the member function definitions; and driver.cpp is a simple client program that uses the Time class. Given the previous detailed examples, this section presents the files with minimal elaboration.
|
|
|||||||||||||||||||||
class Time
{
private:
int hours;
int minutes;
int seconds;
public:
Time() : hours(0), minutes(0), seconds(0) {}
Time(int h, int m, int s)
: hours(h), minutes(m), seconds(s) {}
Time(int s);
Time add(Time t2);
void print();
void read();
};
|
class Time
{
private:
int hours = 0;
int minutes = 0;
int seconds = 0;
public:
Time() {}
Time(int h, int m, int s)
: hours(h), minutes(m), seconds(s) {}
Time(int s);
Time add(Time t2);
void print();
void read();
};
|
private, and member functions are public. Programmers can initialize the member variables with a default constructor, or in the class specification with a "dummy" default constructor. Recognizing that the add, print, and read functions have an implicit this parameter, binding them to an object. This observation is crucial for understanding member function calls.
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;
Time::Time(int s)
{
hours = s / 3600;
s %= 3600;
minutes = s / 60;
seconds = s % 60;
}
void Time::print()
{
cout.fill('0');
cout << hours << ":" << setw(2) << minutes << ":" <<
setw(2) << seconds << endl;
cout.fill(' ');
} |
Time Time::add(Time t2)
{
int i1 = hours * 3600 + minutes * 60 + seconds;
int i2 = t2.hours * 3600 + t2.minutes * 60 + t2.seconds;
return Time(i1 + i2);
}
void Time::read()
{
cout << "Please enter the hours: ";
cin >> hours;
cout << "Please enter the minutes: ";
cin >> minutes;
cout << "Please enter the seconds: ";
cin >> seconds;
}
|
this pointer. The add function illustrates the distinction:
this object
#include <iostream>
#include "Time.h"
using namespace std;
int main()
{
Time t; // (a)
t.read(); // (b)
t.print();
Time s(1, 30, 4); // (c)
s.print();
t.add(s).print(); // (d)
//Time u = t.add(s); // (e)
//u.print();
return 0;
}
this pointer in the member function.
(t.add(s)).print.