Classes: A Deeper Look,: Objectives
Classes: A Deeper Look,: Objectives
Classes: A Deeper Look,: Objectives
Classes:
A Deeper Look,
Part 1
W. S. Gilbert
OBJECTIVES
In this chapter you will learn:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
9.4
(Enhancing Class Time) Provide a constructor that is capable of using the current time from
the time() functiondeclared in the C++ Standard Library header <ctime>to initialize an object
of the Time class.
ANS: [Note: We provide two solutions. The first one only uses function time. The second
one uses several other data member and functions in <ctime> header.]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Time
{
public:
Time(); // constructor
void setTime( int, int, int ); // set hour, minute and second
void printUniversal(); // print time in universal-time format
void printStandard(); // print time in standard-time format
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
bool isLeapYear( int ); // check if input is a leap year
}; // end class Time
#endif
#include <iomanip>
using std::setfill;
using std::setw;
#include <ctime>
using std::time;
#include "Time.h" // include definition of class Time from Time.h
Time::Time()
{
const int
const int
const int
const int
const int
const int
const int
const int
CURRENT_YEAR = 2004;
START_YEAR = 1970;
HOURS_IN_A_DAY = 24;
MINUTES_IN_AN_HOUR = 60;
SECONDS_IN_A_MINUTE = 60;
DAYS_IN_A_YEAR = 365;
DAYS_IN_A_LEAPYEAR = 366;
TIMEZONE_DIFFERENCE = 5;
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
int leapYear = 0;
int days;
// calculate leap year
for ( int y = START_YEAR; y <= CURRENT_YEAR; y++ )
{
if ( isLeapYear( y ) )
leapYear++;
} // end for
int dayTimeInSeconds = time( 0 ) - HOURS_IN_A_DAY *
MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE * (
DAYS_IN_A_YEAR * ( CURRENT_YEAR - START_YEAR ) + leapYear );
// calculate current second, minute and hour
for ( int s = 0; s < SECONDS_IN_A_MINUTE; s++ )
{
for ( int m = 0; m < MINUTES_IN_AN_HOUR; m++ )
{
for ( int h = 0; h <= HOURS_IN_A_DAY; h++ )
{
if ( isLeapYear( CURRENT_YEAR ) )
days = DAYS_IN_A_LEAPYEAR;
else
days = DAYS_IN_A_YEAR;
for ( int d = 0; d <= days; d++ )
{
if ( s + m * SECONDS_IN_A_MINUTE +
h * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE +
d * HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR *
SECONDS_IN_A_MINUTE == dayTimeInSeconds )
{
setTime( h-TIMEZONE_DIFFERENCE, m, s );
} // end if
} // end for
} // end for
} // end for
} // end for
} // end Time constructor
// set new Time value using universal time; ensure that
// the data remains consistent by setting invalid values to zero
void Time::setTime( int h, int m, int s )
{
hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour
minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute
second = ( s >= 0 && s < 60 ) ? s : 0; // validate second
} // end function setTime
// print Time in universal-time format (HH:MM:SS)
void Time::printUniversal()
{
cout << setfill( '0' ) << setw( 2 ) << hour << ":"
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<< setw( 2 ) << minute << ":" << setw( 2 ) << second;
} // end function printUniversal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "Time.h"
int main()
{
Time t; // create Time object
// display current time
cout << "The universal time is ";
t.printUniversal();
cout << "\nThe standard time is ";
t.printStandard();
cout << endl;
return 0;
} // end main
1
2
3
4
5
6
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
7
8
9
10
11
12
13
14
15
16
17
18
public:
Time(); // constructor
void setTime( int, int, int ); // set hour, minute and second
void printUniversal(); // print time in universal-time format
void printStandard(); // print time in standard-time format
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
}; // end class Time
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#endif
#include <iomanip>
using std::setfill;
using std::setw;
#include <ctime>
using std::localtime;
using std::time;
using std::time_t;
#include "Time.h" // include definition of class Time from Time.h
Time::Time()
{
const time_t currentTime = time( 0 );
const tm *localTime = localtime( ¤tTime );
setTime( localTime->tm_hour, localTime->tm_min, localTime->tm_sec );
} // end Time constructor
// set new Time value using universal time; ensure that
// the data remains consistent by setting invalid values to zero
void Time::setTime( int h, int m, int s )
{
hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour
minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute
second = ( s >= 0 && s < 60 ) ? s : 0; // validate second
} // end function setTime
// print Time in universal-time format (HH:MM:SS)
void Time::printUniversal()
{
cout << setfill( '0' ) << setw( 2 ) << hour << ":"
<< setw( 2 ) << minute << ":" << setw( 2 ) << second;
} // end function printUniversal
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6
40
41
42
43
44
45
46
9.6
(Rational Class) Create a class called Rational for performing arithmetic with fractions.
Write a program to test your class.
Use integer variables to represent the private data of the classthe numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is
declared. The constructor should contain default values in case no initializers are provided and
should store the fraction in reduced form. For example, the fraction
2
--4
would be stored in the object as 1 in the numerator and 2 in the denominator. Provide public
member functions that perform each of the following tasks:
a) Adding two Rational numbers. The result should be stored in reduced form.
b) Subtracting two Rational numbers. The result should be stored in reduced form.
c) Multiplying two Rational numbers. The result should be stored in reduced form.
d) Dividing two Rational numbers. The result should be stored in reduced form.
e) Printing Rational numbers in the form a/b, where a is the numerator and b is the denominator.
f) Printing Rational numbers in floating-point format.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void Rational::printRational ()
{
if ( denominator == 0 ) // validates denominator
cout << "\nDIVIDE BY ZERO ERROR!!!" << '\n';
else if ( numerator == 0 ) // validates numerator
cout << 0;
else
cout << numerator << '/' << denominator;
} // end function printRational
void Rational::printRationalAsDouble()
{
cout << static_cast< double >( numerator ) / denominator;
} // end function printRationalAsDouble
void Rational::reduction()
{
int largest;
largest = numerator > denominator ? numerator : denominator;
int gcd = 0; // greatest common divisor
for ( int loop = 2; loop <= largest; loop++ )
if ( numerator % loop == 0 && denominator % loop == 0 )
gcd = loop;
if (gcd != 0)
{
numerator /= gcd;
denominator /= gcd;
} // end if
} // end function reduction
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10
9.7
(Enhancing Class Time) Modify the Time class of Figs. 9.89.9 to include a tick member
function that increments the time stored in a Time object by one second. The Time object should
always remain in a consistent state. Write a program that tests the tick member function in a loop
that prints the time in standard format during each iteration of the loop to illustrate that the tick
member function works correctly. Be sure to test the following cases:
a) Incrementing into the next minute.
b) Incrementing into the next hour.
c) Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
30
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#endif
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
11
12
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
1
2
3
4
5
6
7
8
9
10
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
13
return 0;
} // end main
11:59:57
11:59:58
11:59:59
12:00:00
12:00:01
.
.
.
PM
PM
PM
AM
AM
9.11 (Rectangle Class) Create a class Rectangle with attributes length and width, each of which
defaults to 1. Provide member functions that calculate the perimeter and the area of the rectangle.
Also, provide set and get functions for the length and width attributes. The set functions should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0.
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
1
2
3
4
5
6
7
8
9
10
11
12
#include <iomanip>
using std::setprecision;
#include "Rectangle.h" // include definition of class Rectangle
int main()
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
15
9.15 (TicTacToe Class) Create a class TicTacToe that will enable you to write a complete program
to play the game of tic-tac-toe. The class contains as private data a 3-by-3 two-dimensional array
of integers. The constructor should initialize the empty board to all zeros. Allow two human players.
Wherever the first player moves, place a X in the specified square. Place an O wherever the second
player moves. Each move must be to an empty square. After each move, determine whether the
game has been won or is a draw. If you feel ambitious, modify your program so that the computer
makes the moves for one of the players. Also, allow the player to specify whether he or she wants to
go first or second. If you feel exceptionally ambitious, develop a program that will play three-dimensional tic-tac-toe on a 4-by-4-by-4 board. [Caution: This is an extremely challenging project that
could take many weeks of effort!]
ANS:
1
2
3
4
5
6
7
8
9
10
11
12
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
16
13
14
15
16
17
18
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#endif
#include <iomanip>
using std::setw;
#include "TicTacToe.h" // include definiton of class TicTacToe
TicTacToe::TicTacToe()
{
for ( int j = 0; j < 3; j++ ) // initialize board
for ( int k = 0; k < 3; k++ )
board[ j ][ k ] = ' ';
} // end TicTacToe constructor
bool TicTacToe::validMove( int r, int c )
{
return r >= 0 && r < 3 && c >= 0 && c < 3 && board[ r ][ c ] == ' ';
} // end function validMove
// must specify that type Status is part of the TicTacToe class.
// See Chapter 24 for a discussion of namespaces.
TicTacToe::Status TicTacToe::gameStatus()
{
int a;
// check for a win on diagonals
if ( board[ 0 ][ 0 ] != ' ' && board[ 0 ][ 0 ] == board[ 1 ][ 1 ] &&
board[ 0 ][ 0 ] == board[ 2 ][ 2 ] )
return WIN;
else if ( board[ 2 ][ 0 ] != ' ' && board[ 2 ][ 0 ] ==
board[ 1 ][ 1 ] && board[ 2 ][ 0 ] == board[ 0 ][ 2 ] )
return WIN;
// check for win in rows
for ( a = 0; a < 3; ++a )
if ( board[ a ][ 0 ] != ' ' && board[ a ][ 0 ] ==
board[ a ][ 1 ] && board[ a ][ 0 ] == board[ a ][ 2 ] )
return WIN;
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
17
\n";
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
18
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Solutions
|
|
____|____|____
|
|
1
|
|
____|____|____
|
|
2
|
|
Player X enter move: 2 0
0
|
|
____|____|____
|
|
1
|
|
____|____|____
|
|
2 X |
|
Player O enter move: 2 2
0
|
|
____|____|____
|
|
1
|
|
____|____|____
|
|
2 X |
| O
Player X enter move: 1 1
...
Player X enter move: 0 2
0
|
| X
____|____|____
|
|
1
| X | O
____|____|____
|
|
2 X |
| O
Player X wins!
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
19