Using enums to model cardsUsing class-based enumsClient programs and the Card classHow do objects act like built-in types?Case study: the class ClockTimeUsing the class ClockTimeDesign and Implementation IssuesRelational operatorsFree functions using class methodsClass or Data invariantsImplementing similar classesNiklaus WirthWhat’s in a file, what’s in a string?Basics of the type charChar compared to intChar values as integersFiles as lines of charactersI/O, Files, chars, and troubleUsing istringstream (istrstream) objectsOther file-reading functionsState machines for readingState diagram (decomment.cpp)State machine for /* comments */Defining statesA Computer Science Tapestry9.1Using enums to model cardsConsider the declaration below from card.h, simulate playing cardclass Card{ public: enum Suit {spades, hearts, diamonds, clubs}; Card(); // default, ace of spades Card(int rank, Suit s); bool SameSuitAs(const Card& c) const; int GetRank() const; bool IsJoker() const; private: int myRank; Suit mySuit;};A Computer Science Tapestry9.2Using class-based enumsWe can’t refer to Suit, we must use Card::SuitThe new type Suit is part of the Card classUse Card::Suit to identify the type in client codeCan assign enum to int, but need cast going the other wayint rank, suit;tvector<Card> deck;for(rank=1; rank < 52; rank++){for(suit = Card::spades;suit <= Card::clubs; suit++){ Card c(rank % 13 + 1, Card::Suit(suit)); deck.push_back(c);}}A Computer Science Tapestry9.3Client programs and the Card classDo we need to know about enums to write isFlush()?In a flush, all cards are the same suitSee card.h online, more functions than on previous slideWhat about SameSuitAs function?What about GetRank function?Think behavior before state, do we need the suit?Can cards be compared for ==? What about <?Why would we need these operators?How do we write poker hand three-of-a-kind?What about full house?A Computer Science Tapestry9.4How do objects act like built-in types?We’ve used Date and Bigint objects, and in many cases used the same operations that we use on ints and doublesWe print with operator <<We add using +, +=, and ++We compare using ==, <, >In C++ class objects can be made to act like built-in types by overloading operatorsWe can overload operator << to print to streamsWe can overload operator == to compare Date objectsWe’ll develop a methodology that allows us to easily implement overloaded operators for classes Not all classes should have overloaded operatorsIs overloading + to be the union of sets a good idea?A Computer Science Tapestry9.5Case study: the class ClockTimeRepresents hours, minutes, seconds, e.g., 1:23:47 for one hour, twenty-three minutes, 47 secondsClockTime values can be added, compared, printedclass ClockTime{ public: ClockTime(); ClockTime(int secs, int mins, int hours); int Hours() const; // returns # hours int Minutes() const; // returns # minutes int Seconds() const; // returns # seconds How are values represent internally (private), what are some options?Do client program need to know the representation?A Computer Science Tapestry9.6Using the class ClockTimeThe code below shows how the class can be used, what overloaded operators are shown?int h,m,s;ClockTime total(0,0,0);ClockTime max = total; // zerowhile (cin >> h >> m >> s){ ClockTime t(s,m,h); total += t; if (t > max) { max = t; }}cout << "total time = " << total << endl;cout << "max time = " << max << endl;A Computer Science Tapestry9.7Design and Implementation IssuesConverting to a string facilitates writing to a streamWe know how to write strings, conversion to a string solves many problemsEvery class should have a toString() method – Java doesAn object could be in a bad state, 1 hour 72 min. 87 sec., How can this happen? How do we prevent bad state?Ignore illegal valuesStop the program Convert to something appropriateFor ClockTime class we’ll normalize, convert to standard formA Computer Science Tapestry9.8Relational operatorsRelational operators are implemented as free functions, not class member functions (Tapestry approach, not universal)Needed for symmetry in some cases, see Howto E for detailsWe’ll use member function Equals to implement == Print-to-stream operator << must be a free functionWe’ll use toString to implement <<, avoid using friend functionsostream & operator << (ostream & os, const ClockTime & ct);bool operator == (const ClockTime& lhs, const ClockTime& rhs);These prototypes appear in clockt.h, no code just prototypeCode in header file causes problems with multiple definitions at link timeA Computer Science Tapestry9.9Free functions using class methodsWe can implement == using the Equals method. Note that operator == cannot access myHours, not a problem, why?bool operator == (const ClockTime& lhs, const ClockTime& rhs){ return lhs.Equals(rhs);}We can implement operator << using toString()ostream & operator << (ostream & os, const ClockTime & ct)// postcondition: inserts ct onto os, returns os{ os << ct.ToString(); return os;}Similarly, implement + using +=, what about != and < ?A Computer Science Tapestry9.10Class or Data invariantsA ClockTime object must satisfy class invariant to be validData invariant true of object as viewed by client programCannot have minutes or seconds greater than 60What methods can break the invariant, how do we fix this?A private, helper function Normalize maintains the invariantvoid ClockTime::Normalize()// post: myMinutes < 60, mySeconds < 60, represents same time{ myMinutes += mySeconds/60; mySeconds %= 60; myHours += myMinutes/60; myMinutes %= 60;}A Computer Science Tapestry9.11Implementing similar classesThe class Bigint declared in bigint.h represents integers with no bound on sizeHow might values be stored in the class?What functions will be easier to implement? Why?Implementing rational numbers like 2/4, 3/5, or –22/7Similarities to ClockTime? What private data can we use to define a rational?What will be harder to implement?What about the Date class? How are its operations facilitated by conversion to absolute number of days from 1/1/1 ?A Computer Science Tapestry9.12Niklaus WirthDesigned and implemented several
View Full Document