Classes: A Deeper Look, Part 1

Similar documents
EE 152 Advanced Programming LAB 7

Classes: A Deeper Look, Part 2

Computer Programming with C++ (21)

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

A Deeper Look at Classes

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

Classes: A Deeper Look

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

Classes: A Deeper Look. Systems Programming

Chapter 6: Classes and Data Abstraction

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions

More C++ Classes. Systems Programming

IS 0020 Program Design and Software Tools

57:017, Computers in Engineering C++ Classes

Homework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions

IS 0020 Program Design and Software Tools

Computer Programming Class Members 9 th Lecture

IS 0020 Program Design and Software Tools

Introduction to Programming session 24

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10

Chapter 16: Classes and Data Abstraction

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.

Classes and Objects: A Deeper Look

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions

Chapter 17 - C++ Classes: Part II

Chapter 9 Classes : A Deeper Look, Part 1

OBJECT ORIENTED PROGRAMMING USING C++

Fundamentals of Programming Session 24

Classes and Data Abstraction. Topic 5

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

IS 0020 Program Design and Software Tools

clarity. In the first form, the access specifier public : is needed to {

Object Oriented Design

Classes and Data Abstraction

Chapter 15 - C++ As A "Better C"

UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class

Introduction to Classes

W8.2 Operator Overloading

this Pointer, Constant Functions, Static Data Members, and Static Member Functions this Pointer (11.1) Example of this pointer

Operator Overloading

An inline function is one in which the function code replaces the function call directly. Inline class member functions

Introduction. W8.2 Operator Overloading

CS 1337 Computer Science II Page 1

CIS 190: C/C++ Programming. Classes in C++

Classes and Objects: A Deeper Look

Page 1 of 5. *** person.cpp *** #include "person.h" #include <string> #include <iostream> using namespace std; *** person.h ***

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Classes and Data Abstraction. Topic 5

Chapter 3 - Functions

Operator Overloading

Namespaces and Class Hierarchies

Chapter 7: Classes Part II

Operator overloading: extra examples

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Inheritance and Polymorphism

Classes and Objects. Types and Classes. Example. Object Oriented Programming

Software Development With Java CSCI

6.096 Introduction to C++

Operator Overloading

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Fundamentals of Programming Session 25

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Scope. Scope is such an important thing that we ll review what we know about scope now:

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

Functions and Recursion

Operator Overloading in C++ Systems Programming

Introduction to C++ Systems Programming

Classes and Objects: A Deeper Look

Chapter 3 - Functions

第三章习题答案 // include definition of class GradeBook from GradeBook.h #include "GradeBook.h"

Chapter 19 C++ Inheritance

Software Design Abstract Data Types

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

Chapter 18 - C++ Operator Overloading

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class.

Encapsulation. Contents. Steven Zeil. July 17, Encapsulation Encapsulation in C Classes 4. 3 Hiding Attributes 8

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

SFU CMPT Topic: Classes

UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

Ch 2 ADTs and C++ Classes

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

Object-Based Programming (Deitel chapter 8)

Chapter 19 - C++ Inheritance

Object-Oriented Programming

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers.

Arrays. Week 4. Assylbek Jumagaliyev

Short Notes of CS201

Programming II Lecture 2 Structures and Classes

Transcription:

9 Classes: A Deeper Look, Part 1 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition errors caused by including more than one copy of a header file in a source-code file. To understand class scope and accessing class members via the name of an object, a reference to an object or a pointer to an object. To define constructors with default arguments. How destructors are used to perform termination housekeeping on an object before it is destroyed. When constructors and destructors are called. My object all sublime I shall achieve in time. W. S. Gilbert Is it a world to hide virtues in? William Shakespeare Don t be consistent, but be simply true. Oliver Wendell Holmes, Jr. This above all: to thine own self be true. William Shakespeare The logic errors that may occur when a public member function of a class returns a reference to private data. To assign the data members of one object to those of another object by default memberwise assignment.

Solutions 481 Self-Review Exercises 9.1 Fill in the blanks in each of the following: a) Class members are accessed via the operator in conjunction with the name of an object (or reference to an object) of the class or via the operator in conjunction with a pointer to an object of the class. ANS: dot (.), arrow (->). b) Class members specified as are accessible only to member functions of the class and friends of the class. ANS: private. c) Class members specified as are accessible anywhere an object of the class is in scope. ANS: public. d) can be used to assign an object of a class to another object of the same class. ANS: Default memberwise assignment (performed by the assignment operator). 9.2 Find the error(s) in each of the following and explain how to correct it (them): a) Assume the following prototype is declared in class Time: Solutions void ~Time( int ); ANS: Error: Destructors are not allowed to return values (or even specify a return type) or take arguments. Correction: Remove the return type void and the parameter int from the declaration. b) The following is a partial definition of class Time: class Time { public: // function prototypes private: int hour = 0; int minute = 0; int second = 0; }; // end class Time ANS: Error: Members cannot be explicitly initialized in the class definition. Correction: Remove the explicit initialization from the class definition and initialize the data members in a constructor. c) Assume the following prototype is declared in class Employee: int Employee( const char *, const char * ); ANS: Error: Constructors are not allowed to return values. Correction: Remove the return type int from the declaration. 9.3 What is the purpose of the scope resolution operator? ANS: The scope resolution operator is used to specify the class to which a function belongs. It also resolves the ambiguity caused by multiple classes having member functions of the same name. It also associates a member function in a.cpp file with a class definition in a.h file.

482 Chapter 9 Classes: A Deeper Look, Part 1 9.4 (Enhancing Class Time) Provide a constructor that is capable of using the current time from the time() function declared 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 // Exercise 9.4 Solution: Time.h 2 #ifndef TIME_H 3 #define TIME_H 4 5 class Time 6 { 7 public: 8 Time(); // constructor 9 void settime( int, int, int ); // set hour, minute and second 10 void printuniversal(); // print time in universal-time format 11 void printstandard(); // print time in standard-time format 12 private: 13 int hour; // 0-23 (24-hour clock format) 14 int minute; // 0-59 15 int second; // 0-59 16 bool isleapyear( int ); // check if input is a leap year 17 }; // end class Time 18 19 #endif 1 // Exercise 9.4 Solution: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include <iomanip> 7 using std::setfill; 8 using std::setw; 9 10 #include <ctime> 11 using std::time; 12 13 #include "Time.h" // include definition of class Time from Time.h 14 15 Time::Time() 16 { 17 const int CURRENT_YEAR = 2004; 18 const int START_YEAR = 1970; 19 const int HOURS_IN_A_DAY = 24; 20 const int MINUTES_IN_AN_HOUR = 60; 21 const int SECONDS_IN_A_MINUTE = 60; 22 const int DAYS_IN_A_YEAR = 365; 23 const int DAYS_IN_A_LEAPYEAR = 366; 24 const int TIMEZONE_DIFFERENCE = 5; 25 int leapyear = 0; 26 int days; 27

Solutions 483 28 // calculate leap year 29 for ( int y = START_YEAR; y <= CURRENT_YEAR; y++ ) 30 { 31 if ( isleapyear( y ) ) 32 leapyear++; 33 } // end for 34 35 int daytimeinseconds = time( 0 ) - HOURS_IN_A_DAY * 36 MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE * ( 37 DAYS_IN_A_YEAR * ( CURRENT_YEAR - START_YEAR ) + leapyear ); 38 39 // calculate current second, minute and hour 40 for ( int s = 0; s < SECONDS_IN_A_MINUTE; s++ ) 41 { 42 for ( int m = 0; m < MINUTES_IN_AN_HOUR; m++ ) 43 { 44 for ( int h = 0; h <= HOURS_IN_A_DAY; h++ ) 45 { 46 if ( isleapyear( CURRENT_YEAR ) ) 47 days = DAYS_IN_A_LEAPYEAR; 48 else 49 days = DAYS_IN_A_YEAR; 50 51 for ( int d = 0; d <= days; d++ ) 52 { 53 if ( s + m * SECONDS_IN_A_MINUTE + 54 h * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE + 55 d * HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR * 56 SECONDS_IN_A_MINUTE == daytimeinseconds ) 57 { 58 settime( h-timezone_difference, m, s ); 59 } // end if 60 } // end for 61 } // end for 62 } // end for 63 } // end for 64 } // end Time constructor 65 66 // set new Time value using universal time; ensure that 67 // the data remains consistent by setting invalid values to zero 68 void Time::setTime( int h, int m, int s ) 69 { 70 hour = ( h >= 0 && h < 24 )? h : 0; // validate hour 71 minute = ( m >= 0 && m < 60 )? m : 0; // validate minute 72 second = ( s >= 0 && s < 60 )? s : 0; // validate second 73 } // end function settime 74 75 // print Time in universal-time format (HH:MM:SS) 76 void Time::printUniversal() 77 { 78 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 79 << setw( 2 ) << minute << ":" << setw( 2 ) << second; 80 } // end function printuniversal 81 82 // print Time in standard-time format (HH:MM:SS AM or PM)

484 Chapter 9 Classes: A Deeper Look, Part 1 83 void Time::printStandard() 84 { 85 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" 86 << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) 87 << second << ( hour < 12? " AM" : " PM" ); 88 } // end function printstandard 89 90 // check if a year is a leap year 91 bool Time::isLeapYear( int y ) 92 { 93 if ( ( y % 400 == 0 ) ( ( y % 4 == 0 ) && ( y % 100!= 0 ) ) ) 94 return true; 95 else 96 return false; 97 } // end function isleapyear 1 // Exercise 9.4 Solution: Ex09_04.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Time.h" 7 8 int main() 9 { 10 Time t; // create Time object 11 12 // display current time 13 cout << "The universal time is "; 14 t.printuniversal(); 15 cout << "\nthe standard time is "; 16 t.printstandard(); 17 cout << endl; 18 return 0; 19 } // end main The universal time is 14:54:06 The standard time is 2:54:06 PM 1 // Exercise 9.4 Solution: Time.h 2 #ifndef TIME_H 3 #define TIME_H 4 5 class Time 6 { 7 public: 8 Time(); // constructor 9 void settime( int, int, int ); // set hour, minute and second 10 void printuniversal(); // print time in universal-time format

Solutions 485 11 void printstandard(); // print time in standard-time format 12 private: 13 int hour; // 0-23 (24-hour clock format) 14 int minute; // 0-59 15 int second; // 0-59 16 }; // end class Time 17 18 #endif 1 // Exercise 9.4 Solution: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include <iomanip> 7 using std::setfill; 8 using std::setw; 9 10 #include <ctime> 11 using std::localtime; 12 using std::time; 13 using std::time_t; 14 15 #include "Time.h" // include definition of class Time from Time.h 16 17 Time::Time() 18 { 19 const time_t currenttime = time( 0 ); 20 const tm *localtime = localtime( &currenttime ); 21 settime( localtime->tm_hour, localtime->tm_min, localtime->tm_sec ); 22 } // end Time constructor 23 24 // set new Time value using universal time; ensure that 25 // the data remains consistent by setting invalid values to zero 26 void Time::setTime( int h, int m, int s ) 27 { 28 hour = ( h >= 0 && h < 24 )? h : 0; // validate hour 29 minute = ( m >= 0 && m < 60 )? m : 0; // validate minute 30 second = ( s >= 0 && s < 60 )? s : 0; // validate second 31 } // end function settime 32 33 // print Time in universal-time format (HH:MM:SS) 34 void Time::printUniversal() 35 { 36 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 37 << setw( 2 ) << minute << ":" << setw( 2 ) << second; 38 } // end function printuniversal 39 40 // print Time in standard-time format (HH:MM:SS AM or PM) 41 void Time::printStandard() 42 { 43 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" 44 << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) 45 << second << ( hour < 12? " AM" : " PM" );

486 Chapter 9 Classes: A Deeper Look, Part 1 46 } // end function printstandard 9.5 (Complex Class) Create a class called Complex for performing arithmetic with complex numbers. Write a program to test your class. Complex numbers have the form where i is 1 realpart + imaginarypart * i Use double variables to represent the private data of the class. 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. Provide public member functions that perform the following tasks: a) Adding two Complex numbers: The real parts are added together and the imaginary parts are added together. b) Subtracting two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand. c) Printing Complex numbers in the form (a, b), where a is the real part and b is the imaginary part. ANS: 1 // Exercise 9.5 Solution: Complex.h 2 #ifndef COMPLEX_H 3 #define COMPLEX_H 4 5 class Complex 6 { 7 public: 8 Complex( double = 0.0, double = 0.0 ); // default constructor 9 Complex add( const Complex & ); // function add 10 Complex subtract( const Complex & ); // function subtract 11 void printcomplex(); // print complex number format 12 void setcomplexnumber( double, double ); // set complex number 13 private: 14 double realpart; 15 double imaginarypart; 16 }; // end class Complex 17 18 #endif 1 // Exercise 9.5 Solution: Complex.cpp 2 // Member-function definitions for class Complex. 3 #include <iostream> 4 using std::cout; 5 6 #include "Complex.h" 7 8 Complex::Complex( double real, double imaginary ) 9 {

Solutions 487 10 setcomplexnumber( real, imaginary ); 11 } // end Complex constructor 12 13 Complex Complex::add( const Complex &right ) 14 { 15 return Complex( 16 realpart + right.realpart, imaginarypart + right.imaginarypart ); 17 } // end function add 18 19 Complex Complex::subtract( const Complex &right ) 20 { 21 return Complex( 22 realpart - right.realpart, imaginarypart - right.imaginarypart ); 23 } // end function subtract 24 25 void Complex::printComplex() 26 { 27 cout << '(' << realpart << ", " << imaginarypart << ')'; 28 } // end function printcomplex 29 30 void Complex::setComplexNumber( double rp, double ip ) 31 { 32 realpart = rp; 33 imaginarypart = ip; 34 } // end function setcomplexnumber 1 // Exercise 9.5 Solution: Ex09_05.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Complex.h" 7 8 int main() 9 { 10 Complex a( 1, 7 ), b( 9, 2 ), c; // create three Complex objects 11 12 a.printcomplex(); // output object a 13 cout << " + "; 14 b.printcomplex(); // output object b 15 cout << " = "; 16 c = a.add( b ); // invoke add function and assign to object c 17 c.printcomplex(); // output object c 18 19 cout << '\n'; 20 a.setcomplexnumber( 10, 1 ); // reset realpart and 21 b.setcomplexnumber( 11, 5 ); // and imaginarypart 22 a.printcomplex(); // output object a 23 cout << " - "; 24 b.printcomplex(); // output object b 25 cout << " = "; 26 c = a.subtract( b ); // invoke add function and assign to object c 27 c.printcomplex(); // output object c 28 cout << endl;

488 Chapter 9 Classes: A Deeper Look, Part 1 29 return 0; 30 } // end main (1, 7) + (9, 2) = (10, 9) (10, 1) - (11, 5) = (-1, -4) 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 class the 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 // Exercise 9.6 Solution: Rational.h 2 #ifndef RATIONAL_H 3 #define RATIONAL_H 4 5 class Rational 6 { 7 public: 8 Rational( int = 0, int = 1 ); // default constructor 9 Rational addition( const Rational & ); // function addition 10 Rational subtraction( const Rational & ); // function subtraction 11 Rational multiplication( const Rational & ); // function multi. 12 Rational division( const Rational & ); // function division 13 void printrational (); // print rational format 14 void printrationalasdouble(); // print rational as double format 15 private: 16 int numerator; // integer numerator 17 int denominator; // integer denominator 18 void reduction(); // utility function 19 }; // end class Rational 20 21 #endif 1 // Exercise 9.6 Solution: Rational.cpp 2 // Member-function definitions for class Rational. 3 #include <iostream>

4 using std::cout; 5 6 #include "Rational.h" // include definition of class Rational 7 8 Rational::Rational( int n, int d ) 9 { 10 numerator = n; // sets numerator 11 denominator = d; // sets denominator 12 reduction(); // store the fraction in reduced form 13 } // end Rational constructor 14 15 Rational Rational::addition( const Rational &a ) 16 { 17 Rational t; // creates Rational object 18 19 t.numerator = a.numerator * denominator; 20 t.numerator += a.denominator * numerator; 21 t.denominator = a.denominator * denominator; 22 t.reduction(); // store the fraction in reduced form 23 return t; 24 } // end function addition 25 26 Rational Rational::subtraction( const Rational &s ) 27 { 28 Rational t; // creates Rational object 29 30 t.numerator = s.denominator * numerator; 31 t.numerator -= denominator * s.numerator; 32 t.denominator = s.denominator * denominator; 33 t.reduction(); // store the fraction in reduced form 34 return t; 35 } // end function subtraction 36 37 Rational Rational::multiplication( const Rational &m ) 38 { 39 Rational t; // creates Rational object 40 41 t.numerator = m.numerator * numerator; 42 t.denominator = m.denominator * denominator; 43 t.reduction(); // store the fraction in reduced form 44 return t; 45 } // end function multiplication 46 47 Rational Rational::division( const Rational &v ) 48 { 49 Rational t; // creates Rational object 50 51 t.numerator = v.denominator * numerator; 52 t.denominator = denominator * v.numerator; 53 t.reduction(); // store the fraction in reduced form 54 return t; 55 } // end function division 56 57 void Rational::printRational () 58 { Solutions 489

490 Chapter 9 Classes: A Deeper Look, Part 1 59 if ( denominator == 0 ) // validates denominator 60 cout << "\ndivide BY ZERO ERROR!!!" << '\n'; 61 else if ( numerator == 0 ) // validates numerator 62 cout << 0; 63 else 64 cout << numerator << '/' << denominator; 65 } // end function printrational 66 67 void Rational::printRationalAsDouble() 68 { 69 cout << static_cast< double >( numerator ) / denominator; 70 } // end function printrationalasdouble 71 72 void Rational::reduction() 73 { 74 int largest; 75 largest = numerator > denominator? numerator : denominator; 76 77 int gcd = 0; // greatest common divisor 78 79 for ( int loop = 2; loop <= largest; loop++ ) 80 81 if ( numerator % loop == 0 && denominator % loop == 0 ) 82 gcd = loop; 83 84 if (gcd!= 0) 85 { 86 numerator /= gcd; 87 denominator /= gcd; 88 } // end if 89 } // end function reduction 1 // Exercise 9.6 Solution: Ex09_06.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Rational.h" // include definition of class Rational 7 8 int main() 9 { 10 Rational c( 2, 6 ), d( 7, 8 ), x; // creates three rational objects 11 12 c.printrational(); // prints rational object c 13 cout << " + "; 14 d.printrational(); // prints rational object d 15 x = c.addition( d ); // adds object c and d; sets the value to x 16 17 cout << " = "; 18 x.printrational(); // prints rational object x 19 cout << '\n'; 20 x.printrational(); // prints rational object x 21 cout << " = "; 22 x.printrationalasdouble(); // prints rational object x as double

Solutions 491 23 cout << "\n\n"; 24 25 c.printrational(); // prints rational object c 26 cout << " - "; 27 d.printrational(); // prints rational object d 28 x = c.subtraction( d ); // subtracts object c and d 29 30 cout << " = "; 31 x.printrational(); // prints rational object x 32 cout << '\n'; 33 x.printrational(); // prints rational object x 34 cout << " = "; 35 x.printrationalasdouble(); // prints rational object x as double 36 cout << "\n\n"; 37 38 c.printrational(); // prints rational object c 39 cout << " x "; 40 d.printrational(); // prints rational object d 41 x = c.multiplication( d ); // multiplies object c and d 42 43 cout << " = "; 44 x.printrational(); // prints rational object x 45 cout << '\n'; 46 x.printrational(); // prints rational object x 47 cout << " = "; 48 x.printrationalasdouble(); // prints rational object x as double 49 cout << "\n\n"; 50 51 c.printrational(); // prints rational object c 52 cout << " / "; 53 d.printrational(); // prints rational object d 54 x = c.division( d ); // divides object c and d 55 56 cout << " = "; 57 x.printrational(); // prints rational object x 58 cout << '\n'; 59 x.printrational(); // prints rational object x 60 cout << " = "; 61 x.printrationalasdouble(); // prints rational object x as double 62 cout << endl; 63 return 0; 64 } // end main 1/3 + 7/8 = 29/24 29/24 = 1.20833 1/3-7/8 = -13/24-13/24 = -0.541667 1/3 x 7/8 = 7/24 7/24 = 0.291667 1/3 / 7/8 = 8/21 8/21 = 0.380952

492 Chapter 9 Classes: A Deeper Look, Part 1 9.7 (Enhancing Class Time) Modify the Time class of Figs. 9.8 9.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 // Exercise 9.7 Solution: Time.h 2 #ifndef TIME_H 3 #define TIME_H 4 5 class Time 6 { 7 public: 8 public: 9 Time( int = 0, int = 0, int = 0 ); // default constructor 10 11 // set functions 12 void settime( int, int, int ); // set hour, minute, second 13 void sethour( int ); // set hour (after validation) 14 void setminute( int ); // set minute (after validation) 15 void setsecond( int ); // set second (after validation) 16 17 // get functions 18 int gethour(); // return hour 19 int getminute(); // return minute 20 int getsecond(); // return second 21 22 void tick(); // increment one second 23 void printuniversal(); // output time in universal-time format 24 void printstandard(); // output time in standard-time format 25 private: 26 int hour; // 0-23 (24-hour clock format) 27 int minute; // 0-59 28 int second; // 0-59 29 }; // end class Time 30 31 #endif 1 // Exercise 9.7: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include <iomanip> 7 using std::setfill; 8 using std::setw; 9 10 #include "Time.h" // include definition of class Time from Time.h

Solutions 493 11 12 // Time constructor initializes each data member to zero; 13 // ensures that Time objects start in a consistent state 14 Time::Time( int hr, int min, int sec ) 15 { 16 settime( hr, min, sec ); // validate and set time 17 } // end Time constructor 18 19 // set new Time value using universal time; ensure that 20 // the data remains consistent by setting invalid values to zero 21 void Time::setTime( int h, int m, int s ) 22 { 23 sethour( h ); // set private field hour 24 setminute( m ); // set private field minute 25 setsecond( s ); // set private field second 26 } // end function settime 27 28 // set hour value 29 void Time::setHour( int h ) 30 { 31 hour = ( h >= 0 && h < 24 )? h : 0; // validate hour 32 } // end function sethour 33 34 // set minute value 35 void Time::setMinute( int m ) 36 { 37 minute = ( m >= 0 && m < 60 )? m : 0; // validate minute 38 } // end function setminute 39 40 // set second value 41 void Time::setSecond( int s ) 42 { 43 second = ( s >= 0 && s < 60 )? s : 0; // validate second 44 } // end function setsecond 45 46 // return hour value 47 int Time::getHour() 48 { 49 return hour; 50 } // end function gethour 51 52 // return minute value 53 int Time::getMinute() 54 { 55 return minute; 56 } // end function getminute 57 58 // return second value 59 int Time::getSecond() 60 { 61 return second; 62 } // end function getsecond 63 64 // increment one second 65 void Time::tick()

494 Chapter 9 Classes: A Deeper Look, Part 1 66 { 67 setsecond( getsecond() + 1 ); // increment second by 1 68 69 if ( getsecond() == 0 ) 70 { 71 setminute( getminute() + 1 ); // increment minute by 1 72 73 if ( getminute() == 0 ) 74 sethour( gethour() + 1 ); // increment hour by 1 75 } // end if 76 } // end function tick 77 78 // print Time in universal-time format (HH:MM:SS) 79 void Time::printUniversal() 80 { 81 cout << setfill( '0' ) << setw( 2 ) << gethour() << ":" 82 << setw( 2 ) << getminute() << ":" << setw( 2 ) << getsecond(); 83 } // end function printuniversal 84 85 // print Time in standard-time format (HH:MM:SS AM or PM) 86 void Time::printStandard() 87 { 88 cout << ( ( gethour() == 0 gethour() == 12 )? 12 : gethour() % 12 ) 89 << ":" << setfill( '0' ) << setw( 2 ) << getminute() 90 << ":" << setw( 2 ) << getsecond() << ( hour < 12? " AM" : " PM" ); 91 } // end function printstandard 1 // Exercise 9.7: Ex09_07.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Time.h" // include definition of class Time 7 8 const int MAX_TICKS = 30; 9 10 int main() 11 { 12 Time t; // instantiate object t of class Time 13 14 t.settime( 23, 59, 57 ); // set time 15 16 // output Time object t's values 17 for ( int ticks = 1; ticks < MAX_TICKS; ++ticks ) 18 { 19 t.printstandard(); // invokes function printstandard 20 cout << endl; 21 t.tick(); // invokes function tick 22 } // end for 23 24 return 0; 25 } // end main

Solutions 495 11:59:57 PM 11:59:58 PM 11:59:59 PM 12:00:00 AM 12:00:01 AM... 9.8 (Enhancing Class Date) Modify the Date class of Fig. 9.17 to perform error checking on the initializer values for data members month, day and year. Also, provide a member function nextday to increment the day by one. The Date object should always remain in a consistent state. Write a program that tests function nextday in a loop that prints the date during each iteration to illustrate that nextday works correctly. Be sure to test the following cases: a) Incrementing into the next month. b) Incrementing into the next year. ANS: 1 // Exercise 9.8 Solution: Date.h 2 #ifndef DATE_H 3 #define DATE_H 4 5 class Date 6 { 7 public: 8 Date( int = 1, int = 1, int = 1900 ); // default constructor 9 void print(); // print function 10 void setdate( int, int, int ); // set month, day, year 11 void setmonth( int ); // set month 12 void setday( int ); // set day 13 void setyear( int ); // set year 14 int getmonth(); // get month 15 int getday(); // get day 16 int getyear(); // get year 17 void nextday(); // next day 18 private: 19 int month; // 1-12 20 int day; // 1-31 (except February(leap year), April, June, Sept, Nov) 21 int year; // 1900+ 22 bool leapyear(); // leap year 23 int monthdays(); // days in month 24 }; // end class Date 25 26 #endif 1 // Exercise 9.8 Solution: Date.cpp 2 // Member-function definitions for class Date. 3 #include <iostream> 4 using std::cout; 5 6 #include "Date.h" // include definition of class Date

496 Chapter 9 Classes: A Deeper Look, Part 1 7 8 Date::Date( int m, int d, int y ) 9 { 10 setdate( m, d, y ); // sets date 11 } // end Date constructor 12 13 void Date::setDate( int mo, int dy, int yr ) 14 { 15 setmonth( mo ); // invokes function setmonth 16 setday( dy ); // invokes function setday 17 setyear( yr ); // invokes function setyear 18 } // end function setdate 19 20 void Date::setDay( int d ) 21 { 22 if ( month == 2 && leapyear() ) 23 day = ( d <= 29 && d >= 1 )? d : 1; 24 else 25 day = ( d <= monthdays() && d >= 1 )? d : 1; 26 } // end function setday 27 28 void Date::setMonth( int m ) 29 { 30 month = m <= 12 && m >= 1? m : 1; // sets month 31 } // end function setmonth 32 33 void Date::setYear( int y ) 34 { 35 year = y >= 1900? y : 1900; // sets year 36 } // end function setyear 37 38 int Date::getDay() 39 { 40 return day; 41 } // end function getday 42 43 int Date::getMonth() 44 { 45 return month; 46 } // end function getmonth 47 48 int Date::getYear() 49 { 50 return year; 51 } // end function getyear 52 53 void Date::print() 54 { 55 cout << month << '-' << day << '-' << year << '\n'; // outputs date 56 } // end function print 57 58 void Date::nextDay() 59 { 60 setday( day + 1 ); // increments day by 1 61

Solutions 497 62 if ( day == 1 ) 63 { 64 setmonth( month + 1 ); // increments month by 1 65 66 if ( month == 1 ) 67 setyear( year + 1 ); // increments year by 1 68 } // end if statement 69 } // end function nextday 70 71 bool Date::leapYear() 72 { 73 if ( year % 400 == 0 ( year % 4 == 0 && year % 100!= 0 ) ) 74 return true; // is a leap year 75 else 76 return false; // is not a leap year 77 } // end function leapyear 78 79 int Date::monthDays() 80 { 81 const int days[ 12 ] = 82 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 83 84 return month == 2 && leapyear()? 29 : days[ month - 1 ]; 85 } // end function monthdays 1 // Exercise 9.8 Solution: Ex09_08.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "Date.h" // include definitions of class Date 7 8 int main() 9 { 10 const int MAXDAYS = 16; 11 Date d( 12, 24, 2004 ); // instantiate object d of class Date 12 13 // output Date object d's value 14 for ( int loop = 1; loop <= MAXDAYS; ++loop ) 15 { 16 d.print(); // invokes function print 17 d.nextday(); // invokes function next day 18 } // end for 19 20 cout << endl; 21 return 0; 22 } // end main

498 Chapter 9 Classes: A Deeper Look, Part 1 12-24-2004 12-25-2004 12-26-2004 12-27-2004 12-28-2004 12-29-2004 12-30-2004 12-31-2004 1-1-2005 1-2-2005 1-3-2005 1-4-2005 1-5-2005 1-6-2005 1-7-2005 1-8-2005 9.9 (Combining Class Time and Class Date) Combine the modified Time class of Exercise 9.7 and the modified Date class of Exercise 9.8 into one class called DateAndTime. (In Chapter 12, we will discuss inheritance, which will enable us to accomplish this task quickly without modifying the existing class definitions.) Modify the tick function to call the nextday function if the time increments into the next day. Modify functions printstandard and printuniversal to output the date and time. Write a program to test the new class DateAndTime. Specifically, test incrementing the time into the next day. ANS: 1 // Exercise 9.9 Solution: DateAndTime.h 2 #ifndef DATEANDTIME_H 3 #define DATEANDTIME_H 4 5 class DateAndTime 6 { 7 public: 8 DateAndTime( int = 1, int = 1, int = 1900, 9 int = 0, int = 0, int = 0 ); // default constructor 10 void setdate( int, int, int ); // set month, day, year 11 void setmonth( int ); // set month 12 void setday( int ); // set day 13 void setyear( int ); // set year 14 void nextday(); // next day 15 void settime( int, int, int ); // set hour, minute, second 16 void sethour( int ); // set hour 17 void setminute( int ); // set minute 18 void setsecond( int ); // set second 19 void tick(); // tick function 20 int getmonth(); // get month 21 int getday(); // get day 22 int getyear(); // get year 23 int gethour(); // get hour 24 int getminute(); // get minute 25 int getsecond(); // get second 26 void printstandard(); // print standard time

Solutions 499 27 void printuniversal(); // print universal time 28 private: 29 int month; // 1-12 30 int day; // 1-31 (except February(leap year), April, June, Sept, Nov) 31 int year; // 1900+ 32 int hour; // 0-23 (24 hour clock format) 33 int minute; // 0-59 34 int second; // 0-59 35 bool leapyear(); // leap year 36 int monthdays(); // days in month 37 }; // end class DateAndTime 38 39 #endif 1 // Exercise 9.9 Solution: DateAndTime.cpp 2 // Member function definitions for class DateAndTime. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include "DateAndTime.h" // include definition of class DateAndTime 8 9 DateAndTime::DateAndTime( 10 int m, int d, int y, int hr, int min, int sec ) 11 { 12 setdate( m, d, y ); // sets date 13 settime( hr, min, sec ); // sets time 14 } // end DateAndTime constructor 15 16 void DateAndTime::setDate( int mo, int dy, int yr ) 17 { 18 setmonth( mo ); // invokes function setmonth 19 setday( dy ); // invokes function setday 20 setyear( yr ); // invokes function setyear 21 } // end function setdate 22 23 void DateAndTime::setDay( int d ) 24 { 25 if ( month == 2 && leapyear() ) 26 day = ( d <= 29 && d >= 1 )? d : 1; 27 else 28 day = ( d <= monthdays() && d >= 1 )? d : 1; 29 } // end function setday 30 31 void DateAndTime::setMonth( int m ) 32 { 33 month = m <= 12 && m >= 1? m : 1; // sets month 34 } // end function setmonth 35 36 void DateAndTime::setYear( int y ) 37 { 38 year = y >= 1900? y : 1900; // sets year 39 } // end function setyear 40

500 Chapter 9 Classes: A Deeper Look, Part 1 41 void DateAndTime::nextDay() 42 { 43 setday( day + 1 ); // increments day by 1 44 45 if ( day == 1 ) 46 { 47 setmonth( month + 1 ); // increments month by 1 48 49 if ( month == 1 ) 50 setyear( year + 1 ); // increments year by 1 51 } // end if statement 52 } //end function nextday 53 54 void DateAndTime::setTime( int hr, int min, int sec ) 55 { 56 sethour( hr ); // invokes function sethour 57 setminute( min ); // invokes function setminute 58 setsecond( sec ); // invokes function setsecond 59 } // end function settime 60 61 void DateAndTime::setHour( int h ) 62 { 63 hour = ( h >= 0 && h < 24 )? h : 0; // sets hour 64 } // end function sethour 65 66 void DateAndTime::setMinute( int m ) 67 { 68 minute = ( m >= 0 && m < 60 )? m : 0; // sets minute 69 } // end function setminute 70 71 void DateAndTime::setSecond( int s ) 72 { 73 second = ( s >= 0 && s < 60 )? s : 0; // sets second 74 } // end function setsecond 75 76 void DateAndTime::tick() 77 { 78 setsecond( second + 1 ); // increments second by 1 79 80 if ( second == 0 ) 81 { 82 setminute( minute + 1 ); // increments minute by 1 83 84 if ( minute == 0 ) 85 { 86 sethour( hour + 1 ); // increments hour by 1 87 88 if ( hour == 0 ) 89 nextday(); // increments day by 1 90 } // end if 91 } // end if 92 } // end function tick 93 94 int DateAndTime::getDay() 95 {

Solutions 501 96 return day; 97 } // end function getday 98 99 int DateAndTime::getMonth() 100 { 101 return month; 102 } // end function getmonth 103 104 int DateAndTime::getYear() 105 { 106 return year; 107 } // end function getyear 108 109 int DateAndTime::getHour() 110 { 111 return hour; 112 } // end function gethour 113 114 int DateAndTime::getMinute() 115 { 116 return minute; 117 } // end function getminute 118 119 int DateAndTime::getSecond() 120 { 121 return second; 122 } // end function getsecond 123 124 void DateAndTime::printStandard() 125 { 126 cout << ( ( hour % 12 == 0 )? 12 : hour % 12 ) << ':' 127 << ( minute < 10? "0" : "" ) << minute << ':' 128 << ( second < 10? "0" : "" ) << second 129 << ( hour < 12? " AM " : " PM " ) 130 << month << '-' << day << '-' << year << endl; 131 } // end function printstandard 132 133 void DateAndTime::printUniversal() 134 { 135 cout << ( hour < 10? "0" : "" ) << hour << ':' 136 << ( minute < 10? "0" : "" ) << minute << ':' 137 << ( second < 10? "0" : "" ) << second << " " 138 << month << '-' << day << '-' << year << endl; 139 } // end function printuniversal 140 141 bool DateAndTime::leapYear() 142 { 143 if ( year % 400 == 0 ( year % 4 == 0 && year % 100!= 0 ) ) 144 return true; // is a leap year 145 else 146 return false; // is not a leap year 147 } // end function leapyear 148 149 int DateAndTime::monthDays() 150 {

502 Chapter 9 Classes: A Deeper Look, Part 1 151 const int days[ 12 ] = { 152 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 153 154 return ( month == 2 && leapyear() )? 29 : days[ ( month - 1 ) ]; 155 } // end function monthdays 1 // Exercise 9.9 Solution: Ex09_09.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 6 #include "DateAndTime.h" // include definitions of class DateAndTime 7 8 int main() 9 { 10 const int MAXTICKS = 30; 11 DateAndTime d( 12, 31, 2004, 23, 59, 57 ); // instantiates object d 12 // of class DateAndTime 13 14 for ( int ticks = 1; ticks <= MAXTICKS; ticks++ ) 15 { 16 cout << "Universal time: "; 17 d.printuniversal(); // invokes function printuniversal 18 cout << "Standard time: "; 19 d.printstandard(); // invokes function printstandard 20 d.tick(); // invokes function tick 21 } // end for 22 23 cout << endl; 24 return 0; 25 } // end main Universal time: 23:59:57 12-31-2004 Standard time: 11:59:57 PM 12-31-2004 Universal time: 23:59:58 12-31-2004 Standard time: 11:59:58 PM 12-31-2004 Universal time: 23:59:59 12-31-2004 Standard time: 11:59:59 PM 12-31-2004 Universal time: 00:00:00 1-1-2005 Standard time: 12:00:00 AM 1-1-2005 Universal time: 00:00:01 1-1-2005 Standard time: 12:00:01 AM 1-1-2005... 9.10 (Returning Error Indicators from Class Time s set Functions) Modify the set functions in the Time class of Figs. 9.8 9.9 to return appropriate error values if an attempt is made to set a data mem-

Solutions 503 ber of an object of class Time to an invalid value. Write a program that tests your new version of class Time. Display error messages when set functions return error values. ANS: 1 // Exercise 9.10 Solution: Time.h 2 #ifndef TIME_H 3 #define TIME_H 4 5 class Time 6 { 7 public: 8 Time( int = 0, int = 0, int = 0 ); // default constructor 9 bool settime( int, int, int ); // set hour, minute, second 10 bool sethour( int ); // set hour 11 bool setminute( int ); // set minute 12 bool setsecond( int ); // set second 13 int gethour(); // get hour 14 int getminute(); // get minute 15 int getsecond(); // get second 16 void printuniversal(); // print universal time 17 void printstandard(); // print standard time 18 private: 19 int hour; // 0-23 20 int minute; // 0-59 21 int second; // 0-59 22 }; // end class Time 23 24 #endif 1 // Exercise 9.10 Solution: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include "Time.h" // include definition of class Time 7 8 Time::Time( int hr, int min, int sec ) 9 { 10 settime( hr, min, sec ); 11 } // end Time constructor 12 13 bool Time::setTime( int h, int m, int s ) 14 { 15 bool hourvalid = sethour( h ); // invokes function sethour 16 bool minutevalid = setminute( m ); // invokes function setminute 17 bool secondvalid = setsecond( s ); // invokes function setsecond 18 return hourvalid && minutevalid && secondvalid; 19 } // end function settime 20 21 bool Time::setHour( int hr ) 22 { 23 if ( hr >= 0 && hr < 24 ) 24 {

504 Chapter 9 Classes: A Deeper Look, Part 1 25 hour = hr; 26 return true; // hour is valid 27 } // end if 28 else 29 { 30 hour = 0; 31 return false; // hour is invalid 32 } // end else 33 } // end function sethour 34 35 bool Time::setMinute( int min ) 36 { 37 if ( min >= 0 && min < 60 ) 38 { 39 minute = min; 40 return true; // minute is valid 41 } // end if 42 else 43 { 44 minute = 0; 45 return false; // minute is invalid 46 } // end else 47 } // end function setminute 48 49 bool Time::setSecond( int sec ) 50 { 51 if ( sec >= 0 && sec < 60 ) 52 { 53 second = sec; 54 return true; // second is valid 55 } // end if 56 else 57 { 58 second = 0; 59 return false; // second is invalid 60 } // end else 61 } // end function setsecond 62 63 // return hour value 64 int Time::getHour() 65 { 66 return hour; 67 } // end function gethour 68 69 // return minute value 70 int Time::getMinute() 71 { 72 return minute; 73 } // end function getminute 74 75 // return second value 76 int Time::getSecond() 77 { 78 return second; 79 } // end function getsecond

Solutions 505 80 81 void Time::printUniversal() 82 { 83 cout << ( hour < 10? "0" : "" ) << hour << ':' 84 << ( minute < 10? "0" : "" ) << minute << ':' 85 << ( second < 10? "0" : "" ) << second; 86 } // end function printuniversal 87 88 void Time::printStandard() 89 { 90 cout << ( ( hour % 12 == 0 )? 12 : hour % 12 ) << ':' 91 << ( minute < 10? "0": "" ) << minute << ':' 92 << ( second < 10? "0": "" ) << second 93 << ( hour < 12? " AM" : " PM" ); 94 } // end function printstandard 1 // Exercise 9.10 Solution: Ex09_10.cpp 2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 6 7 #include "Time.h" // include definition of class Time 8 9 int main() 10 { 11 Time time; // the Time object 12 13 14 // all t1 object's times are valid 15 if (!t1.getinvalidtime() ) 16 cout << "Error: invalid time setting(s) attempted." << '\n' 17 << "Invalid setting(s) changed to zero." << '\n'; 18 19 t1.printstandard(); // invokes function print standard 20 21 // object t2 has invalid time settings 22 if (!t2.getinvalidtime() ) 23 cout << "\nerror: invalid time setting(s) attempted.\n" 24 << "Invalid setting(s) changed to zero.\n"; 25 26 t2.printuniversal(); // invokes function print universal 27 cout << endl; 28 29 return 0; 30 } // end main 1 // Exercise 9.10 Solution: Ex09_10.cpp 2 #include <iostream> 3 using std::cin; 4 using std::cout; 5 using std::endl; 6

506 Chapter 9 Classes: A Deeper Look, Part 1 7 #include "Time.h" // include definition of class Time 8 9 int getmenuchoice(); // prototype 10 11 int main() 12 { 13 Time time; // the Time object 14 int choice = getmenuchoice(); 15 int hours; 16 int minutes; 17 int seconds; 18 19 while ( choice!= 4 ) 20 { 21 switch ( choice ) 22 { 23 case 1: // set hour 24 cout << "Enter Hours: "; 25 cin >> hours; 26 27 if (!time.sethour( hours ) ) 28 cout << "Invalid hours." << endl; 29 break; 30 case 2: // set minute 31 cout << "Enter Minutes: "; 32 cin >> minutes; 33 34 if (!time.setminute( minutes ) ) 35 cout << "Invalid minutes." << endl; 36 break; 37 case 3: // set seconds 38 cout << "Enter Seconds: "; 39 cin >> seconds; 40 41 if (!time.setsecond( seconds ) ) 42 cout << "Invalid seconds." << endl; 43 break; 44 } // end switch 45 46 cout << "Hour: " << time.gethour() << " Minute: " 47 << time.getminute() << " Second: " << time.getsecond() << endl; 48 cout << "Universal time: "; 49 time.printuniversal(); 50 cout << " Standard time: "; 51 time.printstandard(); 52 cout << endl; 53 54 choice = getmenuchoice(); 55 } // end while 56 } // end main 57 58 // prints a menu and returns a value corresponding to the menu choice 59 int getmenuchoice() 60 { 61 int choice;

Solutions 507 62 63 cout << "1. Set Hour\n2. Set Minute\n3. Set Second\n" 64 << "4. Exit\nChoice: " << endl; 65 cin >> choice; 66 return choice; 67 } // end function getmenuchoice 1. Set Hour 2. Set Minute 3. Set Second 4. Exit Choice: 1 Enter Hours: 17 Hour: 17 Minute: 0 Second: 0 Universal time: 17:00:00 Standard time: 5:00:00 PM 1. Set Hour 2. Set Minute 3. Set Second 4. Exit Choice: 2 Enter Minutes: 65 Invalid minutes. Hour: 17 Minute: 0 Second: 0 Universal time: 17:00:00 Standard time: 5:00:00 PM 1. Set Hour 2. Set Minute 3. Set Second 4. Exit Choice: 3 Enter Seconds: 23 Hour: 17 Minute: 0 Second: 23 Universal time: 17:00:23 Standard time: 5:00:23 PM 1. Set Hour 2. Set Minute 3. Set Second 4. Exit Choice: 4 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 // Exercise 9.11 Solution: Rectangle.h 2 #ifndef RECTANGLE_H 3 #define RECTANGLE_H 4 5 class Rectangle 6 {

508 Chapter 9 Classes: A Deeper Look, Part 1 7 public: 8 Rectangle( double = 1.0, double = 1.0 ); // default constructor 9 void setwidth( double w ); // set width 10 void setlength( double l ); // set length 11 double getwidth(); // get width 12 double getlength(); // get length 13 double perimeter(); // perimeter 14 double area(); // area 15 private: 16 double length; // 1.0 < length < 20.0 17 double width; // 1.0 < width < 20.0 18 }; // end class Rectangle 19 20 #endif 1 // Exercise 9.11 Solution: Rectangle.cpp 2 // Member-function definitions for class Rectangle. 3 4 #include "Rectangle.h" // include definition of class Rectangle 5 6 Rectangle::Rectangle( double w, double l ) 7 { 8 setwidth(w); // invokes function setwidth 9 setlength(l); // invokes function setlength 10 } // end Rectangle constructor 11 12 void Rectangle::setWidth( double w ) 13 { 14 width = w > 0 && w < 20.0? w : 1.0; // sets width 15 } // end function setwidth 16 17 void Rectangle::setLength( double l ) 18 { 19 length = l > 0 && l < 20.0? l : 1.0; // sets length 20 } // end function setlength 21 22 double Rectangle::getWidth() 23 { 24 return width; 25 } // end function getwidth 26 27 double Rectangle::getLength() 28 { 29 return length; 30 } // end fucntion getlength 31 32 double Rectangle::perimeter() 33 { 34 return 2 * ( width + length ); // returns perimeter 35 } // end function perimeter 36 37 double Rectangle::area() 38 { 39 return width * length; // returns area

Solutions 509 40 } // end function area 1 // Exercise 9.11 Solution: Ex09_11.cpp 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 using std::fixed; 6 7 #include <iomanip> 8 using std::setprecision; 9 10 #include "Rectangle.h" // include definition of class Rectangle 11 12 int main() 13 { 14 Rectangle a, b( 4.0, 5.0 ), c( 67.0, 888.0 ); 15 16 cout << fixed; 17 cout << setprecision( 1 ); 18 19 // output Rectangle a 20 cout << "a: length = " << a.getlength() << "; width = " 21 << a.getwidth() << "; perimeter = " << a.perimeter() 22 << "; area = " << a.area() << '\n'; 23 24 // output Rectangle b 25 cout << "b: length = " << b.getlength() << "; width = " 26 << b.getwidth() << "; perimeter = " << b.perimeter() 27 << "; area = " << b.area() << '\n'; 28 29 // output Rectangle c; bad values attempted 30 cout << "c: length = " << c.getlength() << "; width = " 31 << c.getwidth() << "; perimeter = " << c.perimeter() 32 << "; area = " << c.area() << endl; 33 return 0; 34 } // end main a: length = 1.0; width = 1.0; perimeter = 4.0; area = 1.0 b: length = 5.0; width = 4.0; perimeter = 18.0; area = 20.0 c: length = 1.0; width = 1.0; perimeter = 4.0; area = 1.0 9.12 (Enhancing Class Rectangle) Create a more sophisticated Rectangle class than the one you created in Exercise 9.11. This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a set function that accepts four sets of coordinates and verifies that each of these is in the first quadrant with no single x- or y-coordinate larger than 20.0. The set function also verifies that the supplied coordinates do, in fact, specify a rectangle. Provide member functions that calculate the length, width, perimeter and area. The length is the larger of the two dimensions. Include a predicate function square that determines whether the rectangle is a square. ANS: 1 // Exercise 9.12 Solution: Point.h

510 Chapter 9 Classes: A Deeper Look, Part 1 2 #ifndef POINT_H 3 #define POINT_H 4 5 class Point 6 { 7 public: 8 Point( double = 0.0, double = 0.0 ); // default constructor 9 10 // set and get functions 11 void setx( double ); 12 void sety( double ); 13 double getx(); 14 double gety(); 15 private: 16 double x; // 0.0 <= x <= 20.0 17 double y; // 0.0 <= y <= 20.0 18 }; // end class Point 19 20 #endif 1 // Exercise 9.12 Solution: Point.cpp 2 // Member-function definitions for class Point. 3 4 #include "Point.h" // include definition of class Point 5 6 Point::Point( double xcoord, double ycoord ) 7 { 8 setx( xcoord ); // invoke function setx 9 sety( ycoord ); // invoke function sety 10 } // end Point constructor 11 12 // set x coordinate 13 void Point::setX( double xcoord ) 14 { 15 x = ( xcoord >= 0.0 && xcoord <= 20.0 )? xcoord : 0.0; 16 } // end function setx 17 18 // set y coordinate 19 void Point::setY( double ycoord ) 20 { 21 y = ( ycoord >= 0.0 && ycoord <= 20.0 )? ycoord : 0.0; 22 } // end function sety 23 24 // return x coordinate 25 double Point::getX() 26 { 27 return x; 28 } // end function getx 29 30 // return y coordinate 31 double Point::getY() 32 { 33 return y;

Solutions 511 34 } // end function gety 1 // Exercise 9.12 Solution: Rectangle.h 2 #ifndef RECTANGLE_H 3 #define RECTANGLE_H 4 5 #include "Point.h" // include definition of class Point 6 7 class Rectangle 8 { 9 public: 10 // default constructor 11 Rectangle( Point = Point( 0.0, 1.0 ), Point = Point( 1.0, 1.0 ), 12 Point = Point( 1.0, 0.0 ), Point = Point( 0.0, 0.0 ) ); 13 14 // sets x, y, x2, y2 coordinates 15 void setcoord( Point, Point, Point, Point ); 16 double length(); // length 17 double width(); // width 18 void perimeter(); // perimeter 19 void area(); // area 20 bool square(); // square 21 private: 22 Point point1; 23 Point point2; 24 Point point3; 25 Point point4; 26 }; // end class Rectangle 27 28 #endif 1 // Exercise 9.12 Solution: Rectangle.cpp 2 // Member-function definitions for class Rectangle. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 #include <iomanip> 8 using std::fixed; 9 using std::setprecision; 10 11 #include <cmath> 12 using std::fabs; 13 14 #include "Rectangle.h" // include definition of class Rectangle 15 16 Rectangle::Rectangle( Point a, Point b, Point c, Point d ) 17 { 18 setcoord( a, b, c, d ); // invokes function setcoord 19 } // end Rectangle constructor 20 21 void Rectangle::setCoord( Point p1, Point p2, Point p3, Point p4 ) 22 {

512 Chapter 9 Classes: A Deeper Look, Part 1 23 // Arrangement of points 24 // p4...p3 25 //.. 26 //.. 27 // p1...p2 28 29 // verify that points form a rectangle 30 if ( ( p1.gety() == p2.gety() && p1.getx() == p4.getx() 31 && p2.getx() == p3.getx() && p3.gety() == p4.gety() ) ) 32 { 33 point1 = p1; 34 point2 = p2; 35 point3 = p3; 36 point4 = p4; 37 } // end if 38 else 39 { 40 cout << "Coordinates do not form a rectangle!\n" 41 << "Use default values.\n"; 42 point1 = Point( 0.0, 1.0 ); 43 point2 = Point( 1.0, 1.0 ); 44 point3 = Point( 1.0, 0.0 ); 45 point4 = Point( 0.0, 0.0 ); 46 } // end else 47 } // end function setcoord 48 49 double Rectangle::length() 50 { 51 double side1 = fabs( point4.gety() - point1.gety() ); // get side1 52 double side2 = fabs( point2.getx() - point1.getx() ); // get side2 53 double length = ( side1 > side2? side1 : side2 ); 54 return length; 55 } // end function length 56 57 double Rectangle::width() 58 { 59 double side1 = fabs( point4.gety() - point1.gety() ); // get side1 60 double side2 = fabs( point2.getx() - point1.getx() ); // get side2 61 double width = ( side1 < side2? side1 : side2 ); 62 return width; 63 } // end function width 64 65 void Rectangle::perimeter() 66 { 67 cout << fixed << "\nthe perimeter is: " << setprecision( 1 ) 68 << 2 * ( length() + width() ) << endl; 69 } // end function perimeter 70 71 void Rectangle::area() 72 { 73 cout << fixed << "The area is: " << setprecision( 1 ) 74 << length() * width() << endl; 75 } // end function area 76 77 bool Rectangle::square()

Solutions 513 78 { 79 return ( fabs( point4.gety() - point1.gety() ) == 80 fabs( point2.getx() - point1.getx() ) ); 81 } // end function square 1 // Exercise 9.12 Solution: Ex09_12.cpp 2 #include <iostream> 3 using std::cout; 4 5 #include "Rectangle.h" // include definition of class Rectangle 6 7 int main() 8 { 9 Point w( 1.0, 1.0 ); 10 Point x( 5.0, 1.0 ); 11 Point y( 5.0, 3.0 ); 12 Point z( 1.0, 3.0 ); 13 Point j( 0.0, 0.0 ); 14 Point k( 1.0, 0.0 ); 15 Point m( 1.0, 1.0 ); 16 Point n( 0.0, 1.0 ); 17 Point v( 99.0, -2.3 ); 18 19 Rectangle rectangles[ 4 ]; // array stores four rectangles 20 21 // output rectangles 22 for ( int i = 0; i < 4; i++ ) 23 { 24 cout << "Rectangle" << i + 1 << ":\n"; 25 26 switch ( i ) // initialize four different rectangles 27 { 28 case 0: // first rectangle 29 rectangles[ i ] = Rectangle( z, y, x, w ); 30 break; 31 case 1: // second rectangle 32 rectangles[ i ] = Rectangle( j, k, m, n ); 33 break; 34 case 2: // third rectangle 35 rectangles[ i ] = Rectangle( w, x, m, n ); 36 break; 37 case 3: // fourth rectangle 38 rectangles[ i ] = Rectangle( v, x, y, z ); 39 break; 40 } // end switch 41 42 cout << "length = " << rectangles[ i ].length(); 43 cout << "\nwidth = " << rectangles[ i ].width(); 44 rectangles[ i ].perimeter(); 45 rectangles[ i ].area(); 46 cout << "The rectangle " 47 << ( rectangles[ i ].square()? "is" : "is not" ) 48 << " a square.\n"; 49 } // end for