DOC PREVIEW
Duke CPS 006 - Using enums to model cards

This preview shows page 1-2-23-24 out of 24 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 24 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 24 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 24 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 24 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 24 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

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 cardsConsider 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 enumsWe can’t refer to Suit, we must use Card::SuitThe new type Suit is part of the Card classUse Card::Suit to identify the type in client codeCan 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 classDo we need to know about enums to write isFlush()?In a flush, all cards are the same suitSee card.h online, more functions than on previous slideWhat 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 doublesWe 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 operatorsWe can overload operator << to print to streamsWe can overload operator == to compare Date objectsWe’ll develop a methodology that allows us to easily implement overloaded operators for classes Not all classes should have overloaded operatorsIs overloading + to be the union of sets a good idea?A Computer Science Tapestry9.5Case study: the class ClockTimeRepresents hours, minutes, seconds, e.g., 1:23:47 for one hour, twenty-three minutes, 47 secondsClockTime 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 ClockTimeThe 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 IssuesConverting to a string facilitates writing to a streamWe know how to write strings, conversion to a string solves many problemsEvery class should have a toString() method – Java doesAn 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 valuesStop the program Convert to something appropriateFor ClockTime class we’ll normalize, convert to standard formA Computer Science Tapestry9.8Relational operatorsRelational operators are implemented as free functions, not class member functions (Tapestry approach, not universal)Needed for symmetry in some cases, see Howto E for detailsWe’ll use member function Equals to implement == Print-to-stream operator << must be a free functionWe’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 prototypeCode in header file causes problems with multiple definitions at link timeA Computer Science Tapestry9.9Free functions using class methodsWe 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 invariantsA ClockTime object must satisfy class invariant to be validData invariant true of object as viewed by client programCannot have minutes or seconds greater than 60What 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 classesThe class Bigint declared in bigint.h represents integers with no bound on sizeHow 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/7Similarities 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 WirthDesigned and implemented several


View Full Document

Duke CPS 006 - Using enums to model cards

Download Using enums to model cards
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Using enums to model cards and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Using enums to model cards 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?