50

Click here to load reader

Class Help C++

Embed Size (px)

DESCRIPTION

Deep Look at Class to Create a Program using class method

Citation preview

  • 9Classes: A Deeper Look, Part 1

    O B J E C T I V E SIn 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.

    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.

    My object all sublimeI shall achieve in time.W. S. Gilbert

    Is it a world to hide virtues in?William Shakespeare

    Dont be consistent, but be simply true.Oliver Wendell Holmes, Jr.

    This above all: to thine own self be true.William Shakespeare

    cpphtp5_09_IM.fm Page 480 Thursday, December 23, 2004 4:14 PM

  • Solutions 481

    Self-Review Exercises9.1 Fill in the blanks in each of the following:

    a) Class members are accessed via the operator in conjunction with the nameof an object (or reference to an object) of the class or via the operator inconjunction 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:

    void ~Time( int );

    ANS: Error: Destructors are not allowed to return values (or even specify a return type) ortake arguments.Correction: Remove the return type void and the parameter int from the declara-tion.

    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 initializethe 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.

    Solutions9.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 ofthe same name. It also associates a member function in a .cpp file with a class defini-tion in a .h file.

    cpphtp5_09_IM.fm Page 481 Thursday, December 23, 2004 4:14 PM

  • 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 fromthe time() functiondeclared in the C++ Standard Library header to initialize an objectof the Time class.

    ANS: [Note: We provide two solutions. The first one only uses function time. The secondone uses several other data member and functions in header.]

    1 // Exercise 9.4 Solution: Time.h2 #ifndef TIME_H3 #define TIME_H4 5 class Time 6 {7 public:8 Time(); // constructor9 void setTime( int, int, int ); // set hour, minute and second

    10 void printUniversal(); // print time in universal-time format11 void printStandard(); // print time in standard-time format12 private:13 int hour; // 0 - 23 (24-hour clock format)14 int minute; // 0 - 5915 int second; // 0 - 5916 bool isLeapYear( int ); // check if input is a leap year17 }; // end class Time1819 #endif

    1 // Exercise 9.4 Solution: Time.cpp2 // Member-function definitions for class Time.3 #include 4 using std::cout;56 #include 7 using std::setfill;8 using std::setw;9

    10 #include 11 using std::time;1213 #include "Time.h" // include definition of class Time from Time.h1415 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

    cpphtp5_09_IM.fm Page 482 Thursday, December 23, 2004 4:14 PM

  • Solutions 483

    28 // calculate leap year29 for ( int y = START_YEAR; y = 0 && s < 60 ) ? s : 0; // validate second73 } // end function setTime7475 // print Time in universal-time format (HH:MM:SS)76 void Time::printUniversal()77 {78 cout

  • 484 Chapter 9 Classes: A Deeper Look, Part 1

    83 void Time::printStandard()84 {85 cout

  • Solutions 485

    11 void printStandard(); // print time in standard-time format12 private:13 int hour; // 0 - 23 (24-hour clock format)14 int minute; // 0 - 5915 int second; // 0 - 5916 }; // end class Time1718 #endif

    1 // Exercise 9.4 Solution: Time.cpp2 // Member-function definitions for class Time.3 #include 4 using std::cout;56 #include 7 using std::setfill;8 using std::setw;9

    10 #include 11 using std::localtime;12 using std::time;13 using std::time_t;1415 #include "Time.h" // include definition of class Time from Time.h1617 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 constructor2324 // set new Time value using universal time; ensure that25 // the data remains consistent by setting invalid values to zero26 void Time::setTime( int h, int m, int s )27 {28 hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour29 minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute30 second = ( s >= 0 && s < 60 ) ? s : 0; // validate second31 } // end function setTime3233 // print Time in universal-time format (HH:MM:SS)34 void Time::printUniversal()35 {36 cout

  • 486 Chapter 9 Classes: A Deeper Look, Part 1

    9.5 (Complex Class) Create a class called Complex for performing arithmetic with complex num-bers. Write a program to test your class.

    Complex numbers have the form

    realPart + imaginaryPart * i

    where i is

    Use double variables to represent the private data of the class. Provide a constructor that enablesan object of this class to be initialized when it is declared. The constructor should contain defaultvalues in case no initializers are provided. Provide public member functions that perform the fol-lowing tasks:

    a) Adding two Complex numbers: The real parts are added together and the imaginaryparts are added together.

    b) Subtracting two Complex numbers: The real part of the right operand is subtracted fromthe real part of the left operand, and the imaginary part of the right operand is sub-tracted 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 imag-inary part.

    ANS:

    46 } // end function printStandard

    1 // Exercise 9.5 Solution: Complex.h2 #ifndef COMPLEX_H3 #define COMPLEX_H45 class Complex 6 {7 public:8 Complex( double = 0.0, double = 0.0 ); // default constructor9 Complex add( const Complex & ); // function add

    10 Complex subtract( const Complex & ); // function subtract11 void printComplex(); // print complex number format12 void setComplexNumber( double, double ); // set complex number 13 private:14 double realPart;15 double imaginaryPart;16 }; // end class Complex 1718 #endif

    1 // Exercise 9.5 Solution: Complex.cpp2 // Member-function definitions for class Complex.3 #include 4 using std::cout; 56 #include "Complex.h"78 Complex::Complex( double real, double imaginary )9 {

    1

    cpphtp5_09_IM.fm Page 486 Thursday, December 23, 2004 4:14 PM

  • Solutions 487

    10 setComplexNumber( real, imaginary ); 11 } // end Complex constructor1213 Complex Complex::add( const Complex &right )14 {15 return Complex( 16 realPart + right.realPart, imaginaryPart + right.imaginaryPart );17 } // end function add1819 Complex Complex::subtract( const Complex &right )20 {21 return Complex( 22 realPart - right.realPart, imaginaryPart - right.imaginaryPart );23 } // end function subtract2425 void Complex::printComplex()26 {27 cout

  • 488 Chapter 9 Classes: A Deeper Look, Part 1

    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 denom-inator. Provide a constructor that enables an object of this class to be initialized when it isdeclared. The constructor should contain default values in case no initializers are provided andshould store the fraction in reduced form. For example, the fraction

    would be stored in the object as 1 in the numerator and 2 in the denominator. Provide publicmember 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 de-

    nominator.f) Printing Rational numbers in floating-point format.ANS:

    29 return 0;30 } // end main

    (1, 7) + (9, 2) = (10, 9)(10, 1) - (11, 5) = (-1, -4)

    1 // Exercise 9.6 Solution: Rational.h2 #ifndef RATIONAL_H3 #define RATIONAL_H45 class Rational 6 {7 public:8 Rational( int = 0, int = 1 ); // default constructor9 Rational addition( const Rational & ); // function addition

    10 Rational subtraction( const Rational & ); // function subtraction11 Rational multiplication( const Rational & ); // function multi.12 Rational division( const Rational & ); // function division13 void printRational (); // print rational format14 void printRationalAsDouble(); // print rational as double format15 private:16 int numerator; // integer numerator17 int denominator; // integer denominator18 void reduction(); // utility function19 }; // end class Rational2021 #endif

    1 // Exercise 9.6 Solution: Rational.cpp2 // Member-function definitions for class Rational.3 #include

    24---

    cpphtp5_09_IM.fm Page 488 Thursday, December 23, 2004 4:14 PM

  • Solutions 489

    4 using std::cout; 56 #include "Rational.h" // include definition of class Rational78 Rational::Rational( int n, int d )9 {

    10 numerator = n; // sets numerator11 denominator = d; // sets denominator12 reduction(); // store the fraction in reduced form13 } // end Rational constructor1415 Rational Rational::addition( const Rational &a )16 {17 Rational t; // creates Rational object1819 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 form23 return t;24 } // end function addition2526 Rational Rational::subtraction( const Rational &s )27 {28 Rational t; // creates Rational object 2930 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 form34 return t;35 } // end function subtraction3637 Rational Rational::multiplication( const Rational &m )38 {39 Rational t; // creates Rational object 4041 t.numerator = m.numerator * numerator;42 t.denominator = m.denominator * denominator;43 t.reduction(); // store the fraction in reduced form44 return t;45 } // end function multiplication4647 Rational Rational::division( const Rational &v )48 {49 Rational t; // creates Rational object 5051 t.numerator = v.denominator * numerator; 52 t.denominator = denominator * v.numerator;53 t.reduction(); // store the fraction in reduced form54 return t;55 } // end function division5657 void Rational::printRational ()58 {

    cpphtp5_09_IM.fm Page 489 Thursday, December 23, 2004 4:14 PM

  • 490 Chapter 9 Classes: A Deeper Look, Part 1

    59 if ( denominator == 0 ) // validates denominator60 cout

  • Solutions 491

    23 cout

  • 492 Chapter 9 Classes: A Deeper Look, Part 1

    9.7 (Enhancing Class Time) Modify the Time class of Figs. 9.89.9 to include a tick memberfunction that increments the time stored in a Time object by one second. The Time object shouldalways remain in a consistent state. Write a program that tests the tick member function in a loopthat prints the time in standard format during each iteration of the loop to illustrate that the tickmember 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.h2 #ifndef TIME_H3 #define TIME_H45 class Time 6 {7 public:8 public:9 Time( int = 0, int = 0, int = 0 ); // default constructor

    1011 // set functions12 void setTime( int, int, int ); // set hour, minute, second13 void setHour( int ); // set hour (after validation)14 void setMinute( int ); // set minute (after validation)15 void setSecond( int ); // set second (after validation)1617 // get functions18 int getHour(); // return hour19 int getMinute(); // return minute20 int getSecond(); // return second2122 void tick(); // increment one second23 void printUniversal(); // output time in universal-time format24 void printStandard(); // output time in standard-time format25 private:26 int hour; // 0 - 23 (24-hour clock format)27 int minute; // 0 - 5928 int second; // 0 - 5929 }; // end class Time3031 #endif

    1 // Exercise 9.7: Time.cpp2 // Member-function definitions for class Time.3 #include 4 using std::cout;56 #include 7 using std::setfill;8 using std::setw;9

    10 #include "Time.h" // include definition of class Time from Time.h

    cpphtp5_09_IM.fm Page 492 Thursday, December 23, 2004 4:14 PM

  • Solutions 493

    1112 // 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 1819 // set new Time value using universal time; ensure that20 // the data remains consistent by setting invalid values to zero21 void Time::setTime( int h, int m, int s )22 {23 setHour( h ); // set private field hour24 setMinute( m ); // set private field minute25 setSecond( s ); // set private field second26 } // end function setTime2728 // set hour value29 void Time::setHour( int h )30 {31 hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour32 } // end function setHour3334 // set minute value35 void Time::setMinute( int m )36 {37 minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute38 } // end function setMinute3940 // set second value41 void Time::setSecond( int s )42 {43 second = ( s >= 0 && s < 60 ) ? s : 0; // validate second44 } // end function setSecond4546 // return hour value47 int Time::getHour()48 {49 return hour;50 } // end function getHour5152 // return minute value53 int Time::getMinute()54 {55 return minute;56 } // end function getMinute5758 // return second value59 int Time::getSecond()60 {61 return second;62 } // end function getSecond6364 // increment one second65 void Time::tick()

    cpphtp5_09_IM.fm Page 493 Thursday, December 23, 2004 4:14 PM

  • 494 Chapter 9 Classes: A Deeper Look, Part 1

    66 {67 setSecond( getSecond() + 1 ); // increment second by 16869 if ( getSecond() == 0 ) 70 {71 setMinute( getMinute() + 1 ); // increment minute by 17273 if ( getMinute() == 0 )74 setHour( getHour() + 1 ); // increment hour by 175 } // end if 76 } // end function tick7778 // print Time in universal-time format (HH:MM:SS)79 void Time::printUniversal()80 {81 cout

  • Solutions 495

    9.8 (Enhancing Class Date) Modify the Date class of Fig. 9.17 to perform error checking on theinitializer values for data members month, day and year. Also, provide a member function nextDayto increment the day by one. The Date object should always remain in a consistent state. Write aprogram that tests function nextDay in a loop that prints the date during each iteration to illustratethat nextDay works correctly. Be sure to test the following cases:

    a) Incrementing into the next month.b) Incrementing into the next year.ANS:

    11:59:57 PM11:59:58 PM11:59:59 PM12:00:00 AM12:00:01 AM...

    1 // Exercise 9.8 Solution: Date.h2 #ifndef DATE_H3 #define DATE_H45 class Date 6 {7 public:8 Date( int = 1, int = 1, int = 1900 ); // default constructor9 void print(); // print function

    10 void setDate( int, int, int ); // set month, day, year11 void setMonth( int ); // set month12 void setDay( int ); // set day13 void setYear( int ); // set year14 int getMonth(); // get month15 int getDay(); // get day16 int getYear(); // get year 17 void nextDay(); // next day18 private:19 int month; // 1-1220 int day; // 1-31 (except February(leap year), April, June, Sept, Nov)21 int year; // 1900+22 bool leapYear(); // leap year23 int monthDays(); // days in month 24 }; // end class Date2526 #endif

    1 // Exercise 9.8 Solution: Date.cpp2 // Member-function definitions for class Date.3 #include 4 using std::cout; 56 #include "Date.h" // include definition of class Date

    cpphtp5_09_IM.fm Page 495 Thursday, December 23, 2004 4:14 PM

  • 496 Chapter 9 Classes: A Deeper Look, Part 1

    78 Date::Date( int m, int d, int y ) 9 {

    10 setDate( m, d, y ); // sets date 11 } // end Date constructor1213 void Date::setDate( int mo, int dy, int yr )14 {15 setMonth( mo ); // invokes function setMonth 16 setDay( dy ); // invokes function setDay17 setYear( yr ); // invokes function setYear18 } // end function setDate1920 void Date::setDay( int d )21 {22 if ( month == 2 && leapYear() ) 23 day = ( d = 1 ) ? d : 1; 24 else25 day = ( d = 1 ) ? d : 1;26 } // end function setDay2728 void Date::setMonth( int m ) 29 { 30 month = m = 1 ? m : 1; // sets month 31 } // end function setMonth3233 void Date::setYear( int y ) 34 {35 year = y >= 1900 ? y : 1900; // sets year36 } // end function setYear3738 int Date::getDay() 39 {40 return day;41 } // end function getDay4243 int Date::getMonth() 44 { 45 return month; 46 } // end function getMonth4748 int Date::getYear() 49 { 50 return year; 51 } // end function getYear5253 void Date::print()54 {55 cout

  • Solutions 497

    62 if ( day == 1 ) 63 {64 setMonth( month + 1 ); // increments month by 16566 if ( month == 1 )67 setYear( year + 1 ); // increments year by 168 } // end if statement 69 } // end function nextDay7071 bool Date::leapYear()72 {73 if ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) )74 return true; // is a leap year75 else76 return false; // is not a leap year77 } // end function leapYear7879 int Date::monthDays()80 {81 const int days[ 12 ] = 82 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };8384 return month == 2 && leapYear() ? 29 : days[ month - 1 ];85 } // end function monthDays

    1 // Exercise 9.8 Solution: Ex09_08.cpp2 #include 3 using std::cout; 4 using std::endl; 56 #include "Date.h" // include definitions of class Date78 int main()9 {

    10 const int MAXDAYS = 16;11 Date d( 12, 24, 2004 ); // instantiate object d of class Date1213 // output Date object d's value14 for ( int loop = 1; loop

  • 498 Chapter 9 Classes: A Deeper Look, Part 1

    9.9 (Combining Class Time and Class Date) Combine the modified Time class of Exercise 9.7 andthe modified Date class of Exercise 9.8 into one class called DateAndTime. (In Chapter 12, we willdiscuss inheritance, which will enable us to accomplish this task quickly without modifying the ex-isting class definitions.) Modify the tick function to call the nextDay function if the time incre-ments into the next day. Modify functions printStandard and printUniversal to output the dateand time. Write a program to test the new class DateAndTime. Specifically, test incrementing thetime into the next day.

    ANS:

    12-24-200412-25-200412-26-200412-27-200412-28-200412-29-200412-30-200412-31-20041-1-20051-2-20051-3-20051-4-20051-5-20051-6-20051-7-20051-8-2005

    1 // Exercise 9.9 Solution: DateAndTime.h2 #ifndef DATEANDTIME_H3 #define DATEANDTIME_H45 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, year11 void setMonth( int ); // set month12 void setDay( int ); // set day13 void setYear( int ); // set year14 void nextDay(); // next day15 void setTime( int, int, int ); // set hour, minute, second16 void setHour( int ); // set hour17 void setMinute( int ); // set minute 18 void setSecond( int ); // set second19 void tick(); // tick function 20 int getMonth(); // get month21 int getDay(); // get day22 int getYear(); // get year23 int getHour(); // get hour24 int getMinute(); // get minute25 int getSecond(); // get second 26 void printStandard(); // print standard time

    cpphtp5_09_IM.fm Page 498 Thursday, December 23, 2004 4:14 PM

  • Solutions 499

    27 void printUniversal(); // print universal time28 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-5935 bool leapYear(); // leap year36 int monthDays(); // days in month 37 }; // end class DateAndTime3839 #endif

    1 // Exercise 9.9 Solution: DateAndTime.cpp2 // Member function definitions for class DateAndTime.3 #include 4 using std::cout; 5 using std::endl;67 #include "DateAndTime.h" // include definition of class DateAndTime89 DateAndTime::DateAndTime(

    10 int m, int d, int y, int hr, int min, int sec )11 {12 setDate( m, d, y ); // sets date13 setTime( hr, min, sec ); // sets time14 } // end DateAndTime constructor1516 void DateAndTime::setDate( int mo, int dy, int yr )17 { 18 setMonth( mo ); // invokes function setMonth19 setDay( dy ); // invokes function setday20 setYear( yr ); // invokes function setYear 21 } // end function setDate2223 void DateAndTime::setDay( int d )24 {25 if ( month == 2 && leapYear() )26 day = ( d = 1 ) ? d : 1;27 else28 day = ( d = 1 ) ? d : 1;29 } // end function setDay3031 void DateAndTime::setMonth( int m ) 32 { 33 month = m = 1 ? m : 1; // sets month34 } // end function setMonth3536 void DateAndTime::setYear( int y ) 37 { 38 year = y >= 1900 ? y : 1900; // sets year39 } // end function setYear40

    cpphtp5_09_IM.fm Page 499 Thursday, December 23, 2004 4:14 PM

  • 500 Chapter 9 Classes: A Deeper Look, Part 1

    41 void DateAndTime::nextDay()42 {43 setDay( day + 1 ); // increments day by 14445 if ( day == 1 ) 46 {47 setMonth( month + 1 ); // increments month by 14849 if ( month == 1 )50 setYear( year + 1 ); // increments year by 151 } // end if statement 52 } //end function nextDay5354 void DateAndTime::setTime( int hr, int min, int sec )55 {56 setHour( hr ); // invokes function setHour57 setMinute( min ); // invokes function setMinute58 setSecond( sec ); // invokes function setSecond59 } // end function setTime6061 void DateAndTime::setHour( int h ) 62 { 63 hour = ( h >= 0 && h < 24 ) ? h : 0; // sets hour 64 } // end function setHour6566 void DateAndTime::setMinute( int m ) 67 { 68 minute = ( m >= 0 && m < 60 ) ? m : 0; // sets minute69 } // end function setMinute7071 void DateAndTime::setSecond( int s ) 72 { 73 second = ( s >= 0 && s < 60 ) ? s : 0; // sets second74 } // end function setSecond7576 void DateAndTime::tick()77 {78 setSecond( second + 1 ); // increments second by 17980 if ( second == 0 ) 81 {82 setMinute( minute + 1 ); // increments minute by 18384 if ( minute == 0 ) 85 {86 setHour( hour + 1 ); // increments hour by 18788 if ( hour == 0 )89 nextDay(); // increments day by 190 } // end if 91 } // end if 92 } // end function tick9394 int DateAndTime::getDay() 95 {

    cpphtp5_09_IM.fm Page 500 Thursday, December 23, 2004 4:14 PM

  • Solutions 501

    96 return day; 97 } // end function getDay9899 int DateAndTime::getMonth()100 {101 return month; 102 } // end function getMonth103104 int DateAndTime::getYear() 105 { 106 return year; 107 } // end function getYear108109 int DateAndTime::getHour() 110 { 111 return hour; 112 } // end function getHour113114 int DateAndTime::getMinute() 115 { 116 return minute; 117 } // end function getMinute118119 int DateAndTime::getSecond() 120 { 121 return second; 122 } // end function getSecond123124 void DateAndTime::printStandard()125 {126 cout

  • 502 Chapter 9 Classes: A Deeper Look, Part 1

    9.10 (Returning Error Indicators from Class Times set Functions) Modify the set functions in theTime class of Figs. 9.89.9 to return appropriate error values if an attempt is made to set a data mem-

    151 const int days[ 12 ] = { 152 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };153154 return ( month == 2 && leapYear() ) ? 29 : days[ ( month - 1 ) ];155 } // end function monthDays

    1 // Exercise 9.9 Solution: Ex09_09.cpp2 #include 3 using std::cout; 4 using std::endl; 56 #include "DateAndTime.h" // include definitions of class DateAndTime78 int main()9 {

    10 const int MAXTICKS = 30;11 DateAndTime d( 12, 31, 2004, 23, 59, 57 ); // instantiates object d 12 // of class DateAndTime13 14 for ( int ticks = 1; ticks

  • Solutions 503

    ber of an object of class Time to an invalid value. Write a program that tests your new version of classTime. Display error messages when set functions return error values.

    ANS:

    1 // Exercise 9.10 Solution: Time.h2 #ifndef TIME_H3 #define TIME_H45 class Time 6 {7 public:8 Time( int = 0, int = 0, int = 0 ); // default constructor9 bool setTime( int, int, int ); // set hour, minute, second

    10 bool setHour( int ); // set hour11 bool setMinute( int ); // set minute12 bool setSecond( int ); // set second13 int getHour(); // get hour14 int getMinute(); // get minute15 int getSecond(); // get second16 void printUniversal(); // print universal time17 void printStandard(); // print standard time18 private:19 int hour; // 0-2320 int minute; // 0-5921 int second; // 0-5922 }; // end class Time2324 #endif

    1 // Exercise 9.10 Solution: Time.cpp2 // Member-function definitions for class Time.3 #include 4 using std::cout; 56 #include "Time.h" // include definition of class Time78 Time::Time( int hr, int min, int sec ) 9 {

    10 setTime( hr, min, sec ); 11 } // end Time constructor1213 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 setMinute17 bool secondValid = setSecond( s ); // invokes function setSecond18 return hourValid && minuteValid && secondValid;19 } // end function setTime 2021 bool Time::setHour( int hr )22 {23 if ( hr >= 0 && hr < 24 ) 24 {

    cpphtp5_09_IM.fm Page 503 Thursday, December 23, 2004 4:14 PM

  • 504 Chapter 9 Classes: A Deeper Look, Part 1

    25 hour = hr;26 return true; // hour is valid27 } // end if28 else 29 {30 hour = 0;31 return false; // hour is invalid32 } // end else33 } // end function setHour3435 bool Time::setMinute( int min )36 {37 if ( min >= 0 && min < 60 ) 38 {39 minute = min;40 return true; // minute is valid41 } // end if42 else 43 {44 minute = 0;45 return false; // minute is invalid46 } // end else47 } // end function setMinute4849 bool Time::setSecond( int sec )50 {51 if ( sec >= 0 && sec < 60 ) 52 {53 second = sec;54 return true; // second is valid55 } // end if56 else 57 {58 second = 0;59 return false; // second is invalid60 } // end else61 } // end function setSecond6263 // return hour value64 int Time::getHour()65 {66 return hour;67 } // end function getHour6869 // return minute value70 int Time::getMinute()71 {72 return minute;73 } // end function getMinute7475 // return second value76 int Time::getSecond()77 {78 return second;79 } // end function getSecond

    cpphtp5_09_IM.fm Page 504 Thursday, December 23, 2004 4:14 PM

  • Solutions 505

    8081 void Time::printUniversal()82 {83 cout

  • 506 Chapter 9 Classes: A Deeper Look, Part 1

    7 #include "Time.h" // include definition of class Time89 int getMenuChoice(); // prototype

    1011 int main()12 {13 Time time; // the Time object14 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 hour24 cout > hours;26 27 if ( !time.setHour( hours ) )28 cout

  • Solutions 507

    9.11 (Rectangle Class) Create a class Rectangle with attributes length and width, each of whichdefaults 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 ver-ify that length and width are each floating-point numbers larger than 0.0 and less than 20.0.

    ANS:

    6263 cout

  • 508 Chapter 9 Classes: A Deeper Look, Part 1

    7 public:8 Rectangle( double = 1.0, double = 1.0 ); // default constructor9 void setWidth( double w ); // set width

    10 void setLength( double l ); // set length11 double getWidth(); // get width12 double getLength(); // get length 13 double perimeter(); // perimeter14 double area(); // area15 private:16 double length; // 1.0 < length < 20.017 double width; // 1.0 < width < 20.018 }; // end class Rectangle1920 #endif

    1 // Exercise 9.11 Solution: Rectangle.cpp2 // Member-function definitions for class Rectangle.34 #include "Rectangle.h" // include definition of class Rectangle56 Rectangle::Rectangle( double w, double l )7 {8 setWidth(w); // invokes function setWidth9 setLength(l); // invokes function setLength

    10 } // end Rectangle constructor1112 void Rectangle::setWidth( double w ) 13 { 14 width = w > 0 && w < 20.0 ? w : 1.0; // sets width15 } // end function setWidth1617 void Rectangle::setLength( double l ) 18 { 19 length = l > 0 && l < 20.0 ? l : 1.0; // sets length 20 } // end function setLength2122 double Rectangle::getWidth() 23 { 24 return width; 25 } // end function getWidth2627 double Rectangle::getLength() 28 {29 return length; 30 } // end fucntion getLength3132 double Rectangle::perimeter() 33 { 34 return 2 * ( width + length ); // returns perimeter35 } // end function perimeter3637 double Rectangle::area() 38 { 39 return width * length; // returns area

    cpphtp5_09_IM.fm Page 508 Thursday, December 23, 2004 4:14 PM

  • Solutions 509

    9.12 (Enhancing Class Rectangle) Create a more sophisticated Rectangle class than the one youcreated in Exercise 9.11. This class stores only the Cartesian coordinates of the four corners of therectangle. The constructor calls a set function that accepts four sets of coordinates and verifies thateach of these is in the first quadrant with no single x- or y-coordinate larger than 20.0. The set func-tion also verifies that the supplied coordinates do, in fact, specify a rectangle. Provide member func-tions that calculate the length, width, perimeter and area. The length is the larger of the twodimensions. Include a predicate function square that determines whether the rectangle is a square.

    ANS:

    40 } // end function area

    1 // Exercise 9.11 Solution: Ex09_11.cpp2 #include 3 using std::cout; 4 using std::endl; 5 using std::fixed; 67 #include 8 using std::setprecision; 9

    10 #include "Rectangle.h" // include definition of class Rectangle1112 int main()13 {14 Rectangle a, b( 4.0, 5.0 ), c( 67.0, 888.0 );15 16 cout

  • 510 Chapter 9 Classes: A Deeper Look, Part 1

    2 #ifndef POINT_H3 #define POINT_H45 class Point 6 {7 public:8 Point( double = 0.0, double = 0.0 ); // default constructor9

    10 // set and get functions11 void setX( double );12 void setY( double );13 double getX(); 14 double getY(); 15 private:16 double x; // 0.0

  • Solutions 511

    34 } // end function getY

    1 // Exercise 9.12 Solution: Rectangle.h2 #ifndef RECTANGLE_H3 #define RECTANGLE_H45 #include "Point.h" // include definition of class Point67 class Rectangle 8 {9 public:

    10 // default constructor11 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 coordinates15 void setCoord( Point, Point, Point, Point );16 double length(); // length17 double width(); // width18 void perimeter(); // perimeter19 void area(); // area20 bool square(); // square21 private:22 Point point1; 23 Point point2; 24 Point point3; 25 Point point4; 26 }; // end class Rectangle 2728 #endif

    1 // Exercise 9.12 Solution: Rectangle.cpp2 // Member-function definitions for class Rectangle.3 #include 4 using std::cout; 5 using std::endl;67 #include 8 using std::fixed; 9 using std::setprecision;

    1011 #include 12 using std::fabs;1314 #include "Rectangle.h" // include definition of class Rectangle1516 Rectangle::Rectangle( Point a, Point b, Point c, Point d )17 {18 setCoord( a, b, c, d ); // invokes function setCoord19 } // end Rectangle constructor2021 void Rectangle::setCoord( Point p1, Point p2, Point p3, Point p4 )22 {

    cpphtp5_09_IM.fm Page 511 Thursday, December 23, 2004 4:14 PM

  • 512 Chapter 9 Classes: A Deeper Look, Part 1

    23 // Arrangement of points24 // p4.........p325 // . .26 // . .27 // p1.........p22829 // verify that points form a rectangle30 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 if38 else39 {40 cout

  • 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.cpp2 #include 3 using std::cout;45 #include "Rectangle.h" // include definition of class Rectangle67 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 );1819 Rectangle rectangles[ 4 ]; // array stores four rectangles2021 // output rectangles 22 for ( int i = 0; i < 4; i++ )23 {24 cout

  • 514 Chapter 9 Classes: A Deeper Look, Part 1

    9.13 (Enhancing Class Rectangle) Modify class Rectangle from Exercise 9.12 to include a drawfunction that displays the rectangle inside a 25-by-25 box enclosing the portion of the first quadrantin which the rectangle resides. Include a setFillCharacter function to specify the character out ofwhich the body of the rectangle will be drawn. Include a setPerimeterCharacter function to specifythe character that will be used to draw the border of the rectangle. If you feel ambitious, you mightinclude functions to scale the size of the rectangle, rotate it, and move it around within the desig-nated portion of the first quadrant.

    ANS:

    5051 return 0;52 } // end main

    Rectangle1:length = 4width = 2The perimeter is: 12.0The area is: 8.0The rectangle is not a square.Rectangle2:length = 1.0width = 1.0The perimeter is: 4.0The area is: 1.0The rectangle is a square.Rectangle3:Coordinates do not form a rectangle!Use default values.length = 1.0width = 1.0The perimeter is: 4.0The area is: 1.0The rectangle is a square.Rectangle4:Coordinates do not form a rectangle!Use default values.length = 1.0width = 1.0The perimeter is: 4.0The area is: 1.0The rectangle is a square.

    1 // Exercise 9.13 Solution: Rectangle.h2 #ifndef RECTANGLE_H3 #define RECTANGLE_H45 #include "Point.h" // include definition of class Point67 class Rectangle 8 {9 public:

    10 // default constructor11 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 ),

    cpphtp5_09_IM.fm Page 514 Thursday, December 23, 2004 4:14 PM

  • Solutions 515

    13 char = '*', char = '*' );14 15 // sets x, y, x2, y2 coordinates16 void setCoord( Point, Point, Point, Point );17 double length(); // length18 double width(); // width19 void perimeter(); // perimeter20 void area(); // area21 bool square(); // square22 void draw(); // draw rectangle23 void setPerimeterCharacter( char ); // set perimeter character24 void setFillCharacter( char ); // set fill character25 private:26 Point point1; 27 Point point2; 28 Point point3; 29 Point point4; 30 char fillCharacter;31 char perimeterCharacter;32 }; // end class Rectangle 3334 #endif

    1 // Exercise 9.13 Solution: Rectangle.cpp2 // Member-function definitions for class Rectangle.3 #include 4 using std::cout; 5 using std::endl;67 #include 8 using std::fixed; 9 using std::setprecision;

    1011 #include 12 using std::fabs;1314 #include "Rectangle.h" // include definition of class Rectangle1516 Rectangle::Rectangle( Point a, Point b, Point c, Point d, 17 char fillChar, char perimeterChar )18 {19 setCoord( a, b, c, d ); // invoke function setCoord20 setFillCharacter( fillChar ); // set fill character21 setPerimeterCharacter( perimeterChar ); // set perimeter character22 } // end Rectangle constructor2324 void Rectangle::setCoord( Point p1, Point p2, Point p3, Point p4 )25 {26 // Arrangement of points27 // p4.........p328 // . .29 // . .30 // p1.........p231

    cpphtp5_09_IM.fm Page 515 Thursday, December 23, 2004 4:14 PM

  • 516 Chapter 9 Classes: A Deeper Look, Part 1

    32 // verify that points form a rectangle33 if ( ( p1.getY() == p2.getY() && p1.getX() == p4.getX()34 && p2.getX() == p3.getX() && p3.getY() == p4.getY() ) ) 35 {36 point1 = p1;37 point2 = p2;38 point3 = p3;39 point4 = p4;40 } // end if41 else42 {43 cout

  • Solutions 517

    87 void Rectangle::draw() 88 {89 for ( double y = 25.0; y >= 0.0; y-- ) 90 {91 for ( double x = 0.0; x

  • 518 Chapter 9 Classes: A Deeper Look, Part 1

    9.14 (HugeInteger Class) Create a class HugeInteger that uses a 40-element array of digits tostore integers as large as 40 digits each. Provide member functions input, output, add and sub-stract. For comparing HugeInteger objects, provide functions isEqualTo, isNotEqualTo, isGrea-terThan, isLessThan, isGreaterThanOrEqualTo and isLessThanOrEqualToeach of these is apredicate function that simply returns true if the relationship holds between the two Huge-Integers and returns false if the relationship does not hold. Also, provide a predicate function is-Zero. If you feel ambitious, provide member functions multiply, divide and modulus.

    ANS:

    3 #include "Rectangle.h" // include definition of class Rectangle45 int main()6 {7 Point point1( 12.0, 12.0 );8 Point point2( 18.0, 12.0 );9 Point point3( 18.0, 20.0 );

    10 Point point4( 12.0, 20.0 );11 Rectangle rectangle( point1, point2, point3, point4, '?', '*' ); 12 rectangle.draw(); // invokes function draw13 return 0;14 } // end main

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    ............*******.......

    ............*?????*.......

    ............*?????*.......

    ............*?????*.......

    ............*?????*.......

    ............*?????*.......

    ............*?????*.......

    ............*?????*.......

    ............*******.......

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    ..........................

    1 // Exercise 9.14 Solution: HugeInteger.h2 // HugeInteger class definition.3 #ifndef HUGEINTEGER_H4 #define HUGEINTEGER_H5

    cpphtp5_09_IM.fm Page 518 Thursday, December 23, 2004 4:14 PM

  • Solutions 519

    6 class HugeInteger 7 {8 public:9

    10 HugeInteger( long = 0 ); // conversion/default constructor11 HugeInteger( const char * ); // copy constructor1213 // addition operator; HugeInteger + HugeInteger14 HugeInteger add( const HugeInteger & );1516 // addition operator; HugeInteger + int17 HugeInteger add( int ); 1819 // addition operator; 20 // HugeInteger + string that represents large integer value21 HugeInteger add( const char * ); 2223 // subtraction operator; HugeInteger - HugeInteger24 HugeInteger subtract( const HugeInteger & ); 2526 // subtraction operator; HugeInteger - int27 HugeInteger subtract( int ); 2829 // subtraction operator; 30 // HugeInteger - string that represents large integer value31 HugeInteger subtract( const char * ); 3233 bool isEqualTo( HugeInteger & ); // is equal to34 bool isNotEqualTo( HugeInteger & ); // not equal to35 bool isGreaterThan(HugeInteger & ); // greater than36 bool isLessThan( HugeInteger & ); // less than37 bool isGreaterThanOrEqualTo( HugeInteger & ); // greater than 38 // or equal to39 bool isLessThanOrEqualTo( HugeInteger & ); // less than or equal40 bool isZero(); // is zero41 void input( const char * ); // input42 void output(); // output 43 short* getInteger(); // get integer44 private:45 short integer[ 40 ]; // 40 element array46 }; // end class HugeInteger4748 #endif

    1 // Exercise 9.14 Solution: HugeInteger.cpp2 // Member-function definitions for class HugeInteger.3 #include 4 using std::cin;5 using std::cout;67 #include "HugeInteger.h" // include definiton of class HugeInteger 89 // default constructor; conversion constructor that converts

    10 // a long integer into a HugeInteger object

    cpphtp5_09_IM.fm Page 519 Thursday, December 23, 2004 4:14 PM

  • 520 Chapter 9 Classes: A Deeper Look, Part 1

    11 HugeInteger::HugeInteger( long value )12 {13 // initialize array to zero14 for ( int i = 0; i < 40; i++ )15 integer[ i ] = 0; 1617 // place digits of argument into array 18 for ( int j = 39; value != 0 && j >= 0; j-- ) 19 {20 integer[ j ] = static_cast< short > ( value % 10 );21 value /= 10;22 } // end inner for23 } // end HugeInteger constructor2425 // copy constructor; 26 // converts a char string representing a large integer into a HugeInteger27 HugeInteger::HugeInteger( const char *string )28 {29 this->input( string ); // call input to initialize HugeInteger30 } // end HugeInteger constructor3132 // addition operator; HugeInteger + HugeInteger33 HugeInteger HugeInteger::add( const HugeInteger &op2 )34 {35 HugeInteger temp; // temporary result36 int carry = 0;3738 // iterate through HugeInteger39 for ( int i = 39; i >= 0; i-- ) 40 {41 temp.integer[ i ] = 42 integer[ i ] + op2.integer[ i ] + carry;4344 // determine whether to carry a 145 if ( temp.integer[ i ] > 9 ) 46 {47 temp.integer[ i ] %= 10; // reduce to 0-948 carry = 1;49 } // end if50 else // no carry51 carry = 0;52 } // end for5354 return temp; // return the sum55 } // end function add5657 // addition operator; HugeInteger + int58 HugeInteger HugeInteger::add( int op2 )59 { 60 // convert op2 to a HugeInteger, then invoke add61 return this->add( HugeInteger( op2 ) ); 62 } // end function add63 64 // HugeInteger + string that represents large integer value65 HugeInteger HugeInteger::add( const char *op2 )

    cpphtp5_09_IM.fm Page 520 Thursday, December 23, 2004 4:14 PM

  • Solutions 521

    66 { 67 // convert op2 to a HugeInteger, then invoke add68 return this->add( HugeInteger( op2 ) ); 69 } // end function add7071 // function to subtract two HugeIntegers72 HugeInteger HugeInteger::subtract( const HugeInteger &op2 )73 {74 HugeInteger temp; // temporary result75 int borrow = 0;76 77 // iterate through HugeInteger78 for ( int i = 39; i >= 0; i-- ) 79 {80 // determine to add 10 to smaller integer 81 if ( integer[i] < op2.integer[i] )82 {83 temp.integer[ i ] = 84 ( integer[ i ] + 10 ) - op2.integer[ i ] - borrow;85 borrow = 1; // set borrow to one86 } // end if87 else // if borrowing is not needed88 {89 temp.integer[ i ] = 90 integer[ i ] - op2.integer[ i ] - borrow;91 borrow = 0; // set borrow to zero92 } // end else93 } // end for9495 return temp; // return difference of two HugeIntegers96 } // end function subtract9798 // function to subtract an integer from a HugeInteger99 HugeInteger HugeInteger::subtract( int op2 )100 { 101 // convert op2 to a HugeInteger, then invoke subtract102 return this->subtract( HugeInteger( op2 ) ); 103 } // end function subtract104105 // function that takes string represeting a number106 // and subtracts it from a HugeInteger107 HugeInteger HugeInteger::subtract( const char *op2 )108 { 109 // convert op2 to a HugeInteger, then invoke subtract110 return this->subtract( HugeInteger( op2 ) ); 111 } // end function subtract112113 // function that tests if two HugeIntegers are equal114 bool HugeInteger::isEqualTo( HugeInteger &x )115 {116 return integer == x.getInteger(); 117 } // end function isEqualTo118 119 // function that tests if two HugeIntegers are not equal120 bool HugeInteger::isNotEqualTo( HugeInteger &x )

    cpphtp5_09_IM.fm Page 521 Thursday, December 23, 2004 4:14 PM

  • 522 Chapter 9 Classes: A Deeper Look, Part 1

    121 {122 return !( this->isEqualTo( x ) ); 123 } // end function isNotEqualTo124125 // function to test if one HugeInteger is greater than another126 bool HugeInteger::isGreaterThan( HugeInteger &x ) 127 { 128 return integer < x.getInteger(); 129 } // end function isGreaterThan130131 // function that tests if one HugeInteger is less than another132 bool HugeInteger::isLessThan( HugeInteger &x ) 133 { 134 return integer > x.getInteger(); 135 } // end function isLessThan136137 // function that tests if one HugeInteger is greater than138 // or equal to another139 bool HugeInteger::isGreaterThanOrEqualTo( HugeInteger &x )140 {141 return integer = x.getInteger();149 } // end function isLessThanOrEqualTo150151 // function that tests if a HugeInteger is zero152 bool HugeInteger::isZero()153 {154 return ( getInteger() == 0 );155 } // end function isZero156157 // converts a char string representing a large integer into a HugeInteger158 void HugeInteger::input( const char *string )159 {160 // initialize array to zero161 for ( int i = 0; i < 40; i++ )162 integer[ i ] = 0;163164 // place digits of argument into array165 int length = strlen( string );166167 for ( int j = 40 - length, k = 0; j < 40; j++, k++ )168169 if ( isdigit( string[ k ] ) )170 integer[ j ] = string[ k ] - '0';171 } // end function input172173 // overloaded output operator174 void HugeInteger::output()175 {

    cpphtp5_09_IM.fm Page 522 Thursday, December 23, 2004 4:14 PM

  • Solutions 523

    176 int i; // used for looping177178 for ( i = 0; ( integer[ i ] == 0 ) && ( i

  • 524 Chapter 9 Classes: A Deeper Look, Part 1

    36 // checks for equality between n1 and n1 37 if ( n1.isEqualTo( n1 ) == true )38 { 39 n1.output(); 40 cout

  • Solutions 525

    9.15 (TicTacToe Class) Create a class TicTacToe that will enable you to write a complete programto play the game of tic-tac-toe. The class contains as private data a 3-by-3 two-dimensional arrayof 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 secondplayer moves. Each move must be to an empty square. After each move, determine whether thegame has been won or is a draw. If you feel ambitious, modify your program so that the computermakes the moves for one of the players. Also, allow the player to specify whether he or she wants togo first or second. If you feel exceptionally ambitious, develop a program that will play three-dimen-sional tic-tac-toe on a 4-by-4-by-4 board. [Caution: This is an extremely challenging project thatcould take many weeks of effort!]

    ANS:

    91 if ( n3.isZero() != true )92 {93 cout

  • 526 Chapter 9 Classes: A Deeper Look, Part 1

    1819 #endif

    1 // Exercise 9.15 Solution: TicTacToe.cpp2 // Member-function definitions for class TicTacToe.3 #include 4 using std::cin; 5 using std::cout; 67 #include 8 using std::setw; 9

    10 #include "TicTacToe.h" // include definiton of class TicTacToe1112 TicTacToe::TicTacToe()13 {14 for ( int j = 0; j < 3; j++ ) // initialize board1516 for ( int k = 0; k < 3; k++ )17 board[ j ][ k ] = ' ';18 } // end TicTacToe constructor1920 bool TicTacToe::validMove( int r, int c )21 {22 return r >= 0 && r < 3 && c >= 0 && c < 3 && board[ r ][ c ] == ' ';23 } // end function validMove2425 // must specify that type Status is part of the TicTacToe class.26 // See Chapter 24 for a discussion of namespaces.27 TicTacToe::Status TicTacToe::gameStatus()28 { 29 int a;3031 // check for a win on diagonals32 if ( board[ 0 ][ 0 ] != ' ' && board[ 0 ][ 0 ] == board[ 1 ][ 1 ] &&33 board[ 0 ][ 0 ] == board[ 2 ][ 2 ] )34 return WIN;35 else if ( board[ 2 ][ 0 ] != ' ' && board[ 2 ][ 0 ] == 36 board[ 1 ][ 1 ] && board[ 2 ][ 0 ] == board[ 0 ][ 2 ] )37 return WIN;3839 // check for win in rows40 for ( a = 0; a < 3; ++a )4142 if ( board[ a ][ 0 ] != ' ' && board[ a ][ 0 ] == 43 board[ a ][ 1 ] && board[ a ][ 0 ] == board[ a ][ 2 ] )44 return WIN;4546 // check for win in columns47 for ( a = 0; a < 3; ++a )4849 if ( board[ 0 ][ a ] != ' ' && board[ 0 ][ a ] == 50 board[ 1 ][ a ] && board[ 0 ][ a ] == board[ 2 ][ a ] )51 return WIN;

    cpphtp5_09_IM.fm Page 526 Thursday, December 23, 2004 4:14 PM

  • Solutions 527

    5253 // check for a completed game54 for ( int r = 0; r < 3; ++r )5556 for ( int c = 0; c < 3; ++c )5758 if ( board[ r ][ c ] == ' ' )59 return CONTINUE; // game is not finished6061 return DRAW; // game is a draw62 } // end function gameStatus6364 void TicTacToe::printBoard() 65 {66 cout

  • 528 Chapter 9 Classes: A Deeper Look, Part 1

    107 cout x >> y;110 cout

  • Solutions 529

    0 1 2

    0 | | ____|____|____ | |1 | | ____|____|____ | |2 | |

    Player X enter move: 2 0

    0 1 2

    0 | | ____|____|____ | |1 | | ____|____|____ | |2 X | |

    Player O enter move: 2 2

    0 1 2

    0 | | ____|____|____ | |1 | | ____|____|____ | |2 X | | O

    Player X enter move: 1 1...Player X enter move: 0 2

    0 1 2

    0 | | X ____|____|____ | |1 | X | O ____|____|____ | |2 X | | O

    Player X wins!

    cpphtp5_09_IM.fm Page 529 Thursday, December 23, 2004 4:14 PM

    Statement1: 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist. No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher.

    For the exclusive use of adopters of the book C++ How to Program, 5th Edition,by Deitel and Deitel. ISBN 0-13-185757-6.Deitel: Copyright 1992-2005 by Deitel & Associates, Inc. All Rights Reserved.