Presentation is loading. Please wait.

Presentation is loading. Please wait.

Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes.

Similar presentations


Presentation on theme: "Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes."— Presentation transcript:

1 Using Classes Chapter 5

2 C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes Study I/O classes istream and ostream Study the string class Look at a user-defined random integer class Take a first look at developing instance methods

3 C++ An Introduction to Computing, 3rd ed. 3 Intro Example Consider displaying the song, "Farmer in the Dell" The farmer in the dell The farmer in the dell Hi-Ho, the derry-o The farmer in the dell The farmer takes a wife The farmer takes a wife Hi-Ho, the derry-o The farmer takes a wife... The farmer in the dell The farmer in the dell Hi-Ho, the derry-o The farmer in the dell The farmer takes a wife The farmer takes a wife Hi-Ho, the derry-o The farmer takes a wife... Note the repetition. To print the song, we do NOT want a lot of cout lines, one for each line of the song.

4 C++ An Introduction to Computing, 3rd ed. 4 Intro Example Each verse is the same pattern "The restOfLine" three times "Hi-Ho, the derry-o" between 2 nd and 3 rd lines. The farmer in the dell The farmer in the dell Hi-Ho, the derry-o The farmer in the dell The farmer takes a wife The farmer takes a wife Hi-Ho, the derry-o The farmer takes a wife... The farmer in the dell The farmer in the dell Hi-Ho, the derry-o The farmer in the dell The farmer takes a wife The farmer takes a wife Hi-Ho, the derry-o The farmer takes a wife... Desired Behavior: Display on the screen the lyrics of a verse Work through the verses

5 C++ An Introduction to Computing, 3rd ed. 5 Objects, Operations Operations: i. Display a string on the screen ii. Construct a verse of the song using one of the constant strings Description Software Objects TypeKindName screen ostream varying cout lyrics of Farmer-in-the- Dell verse string constant "farmer in the dell" string constant "farmer takes a wife" string constant... string constant

6 C++ An Introduction to Computing, 3rd ed. 6 Algorithm Note the "Construct a verse of the song using …" Not predefined in C++ We design a function to perform the task Then call that function 10 times Once for each verse's phrase

7 C++ An Introduction to Computing, 3rd ed. 7 Function Behavior, Objects Behavior Receive phrase from caller for 1 st, 2 nd, 4 th line of each verse Construct verse Return verse to calling function Objects Description Software Objects TypeKindMovementName screen ostream varying cout a phrase string varyingreceived (in) restOfLine a verse of song string constantreturned (out) aVerse

8 C++ An Introduction to Computing, 3rd ed. 8 Function Operations, Algorithm Function Operations i. Build aVerse consisting of lyric from restOfLine in 1 st, 2 nd, 3 rd lines ii. Return aVerse to caller Algorithm 1. aVerse = "\nThe" + restOfLine+ "\nThe "+restOfLine+ "\nHi-Ho, the derry-o"+ "\nThe "+restOfLine. 2. Return aVerse

9 C++ An Introduction to Computing, 3rd ed. 9 Coding, Testing View Source code, Figure 5.1 Note:Figure 5.1 Prototype Call of function Function definition Note sample run of Figure 5.1sample run

10 C++ An Introduction to Computing, 3rd ed. 10 Review of Classes We can model many items by declaring variables, constants using predefined types Other objects need multiple attributes declared We encapsulate characteristics of an object within a single wrapper – a class The characteristics are instance variables or data members or attribute variables of the class

11 C++ An Introduction to Computing, 3rd ed. 11 Class Objects The name of a class is used to declare objects or instances of the class. Car dadsCar, momsCar; Now all the attributes of a Car variable can be manipulated as a single entity Send as a single parameter Assign to another Car variable, etc.

12 C++ An Introduction to Computing, 3rd ed. 12 Encapsulating Operations We can package more than data characteristics We can package functions that make up Operations Messages to be sent to objects These are called instance methods or function members They perform specific operations using the data members of the class

13 C++ An Introduction to Computing, 3rd ed. 13 Instance Methods We send to an instance of the object, a message to do a task dadsCar.print(); momsCar.read(); Also possible to redefine operators for classes Redefine + for string objects Redefine > for Car objects Called overloading a function or operator

14 C++ An Introduction to Computing, 3rd ed. 14 The istream Class istream is a class which represents a flow of characters from an input device cin is an object predefined from the istream library – a keyboard input stream

15 C++ An Introduction to Computing, 3rd ed. 15 The istream Class The >> operator is defined in the istream class to extract a sequence of characters int age; cin >> age; The operator is defined so as to interpret the characters according to the type of the variable

16 C++ An Introduction to Computing, 3rd ed. 16 The istream Class One of the attributes of the class is a status value If invalid values are entered for a given type the status is set to a "fail" state Functions provided to check the status MessageReturns True if and only if cin.good() all is well with the istream cin.bad() something is wrong with the istream cin.fail() the last operation cold not be completed

17 C++ An Introduction to Computing, 3rd ed. 17 The istream Class Functions provided to manipulate the status of stream flags By default the >> operator skips leading white space tabs blanks carriage returns MessageAction Taken.clear() re-enables input operations for an istream object.ignore() removes unwanted input from a stream

18 C++ An Introduction to Computing, 3rd ed. 18 The istream Class Input manipulators Identifiers which change some property of the istream Example: cin >> … >> noskipws >> … ; Subsequent white space characters not skipped

19 C++ An Introduction to Computing, 3rd ed. 19 The ostream Class The iostream library provides the ostream class ostream objects cout standard stream for normal output display cerr, clog standard output stream for displaying errors and diagnostics

20 C++ An Introduction to Computing, 3rd ed. 20 The ostream Class The << operator is defined in the ostream class to insert a sequence of characters into the stream Example const double PI = 3.1416; cout << PI;

21 C++ An Introduction to Computing, 3rd ed. 21 The ostream Class Output manipulators Identifiers that affects the ostream when used in the output statement cout << "The answer = " << total << endl; The endl is the same as a '\n' or a newline character Causes output to be flushed from the ostream

22 C++ An Introduction to Computing, 3rd ed. 22 The ostream Class Format control – use format manipulators fixed used fixed point notation, reals showpoint show decimal pt., trailing zeros right right justify values, pad left left left justify values, pad right Example: cout << "\nTotal cost = $" << fixed << showpoint << cost << endl; Note more extensive table of format manipulators on page 233

23 C++ An Introduction to Computing, 3rd ed. 23 The ostream Class Format manipulators with arguments setprecision(n) specify decimal digits setw(n) specify width of field These require #include Example cout << "\nTotal cost = $" << fixed << showpoint << setprecision(2) << cost << endl;

24 C++ An Introduction to Computing, 3rd ed. 24 string Objects string is the name of a class Thus it is a type string lastName; Used in a declaration Creates a string object Initializes it to an empty string Other declarations (with initialization) string play = "Hamlet";

25 C++ An Introduction to Computing, 3rd ed. 25 string I/O The string class has overloaded the > operators Can do I/O directly with string objects string name, prompt = "Enter name : "; cout > name; string input and whitespace Skips leading whitespace characters Quits reading when whitespace encountered

26 C++ An Introduction to Computing, 3rd ed. 26 Other string Operations Subscript operation Access individual characters of a string string name = "John Doe"; cout << name [2]; Size method Determine number of characters in the string cout << name.size(); Empty method Returns true if string is empty 8 characters

27 C++ An Introduction to Computing, 3rd ed. 27 Other string Operations Assignment operator Assign values to string objects string yesterday, today = "Monday"; Relational operator Elements of string operands compared character by character yesterday = today; today = "Tuesday"; string hisName = "James", herName = "Jan"; How does hisName < herName evaluate? True or False?

28 C++ An Introduction to Computing, 3rd ed. 28 Other string Operations Concatenation Combining two strings into a single string string state = "Michigan", greatLake; greatLake = "Lake "+state; The substr(first, num_chars) method Returns a string from first for num_chars cout << greatLake.substr(2,4); What gets printed?

29 C++ An Introduction to Computing, 3rd ed. 29 Other string Operations The replace(first, num_chars, replace) method Replaces the contents of the replace string starting at first, for num_chars Given What is the end result of fullname.replace(5,6,"Eyre"); Six characters replaced with four.

30 C++ An Introduction to Computing, 3rd ed. 30 Other string Operations The insert(position, new_string) method Inserts a substring into a string Given What is the result of signature.insert (5,"E. ");

31 C++ An Introduction to Computing, 3rd ed. 31 Other string Operations The find(pattern, position) and rfind(pattern, position) methods These do pattern matching Searches for the specified pattern starting at the given position Returns the index of where it is found (returns value of string::npos if not found) rfind searches from right to left The find_first_of(pattern, position) method Looks for first character from any in pattern starting at position

32 Problem Session Working in groups of two, solve the following problem...

33 C++ An Introduction to Computing, 3rd ed. 33 Problem Using OCD, design and implement a function that, Given a string containing a long-distance telephone number, Decomposes that number into its Area code (if the first number is a 1) Exchange Local number. Only these two if the first number is not a 1

34 C++ An Introduction to Computing, 3rd ed. 34 Behavior Enter Phone number -> 12345556789 This is a valid number. Area code : 234 Exchange : 555 Local No. : 6789

35 C++ An Introduction to Computing, 3rd ed. 35 Objects Use description to fill in chart for objects. Description Software Objects TypeKindName

36 C++ An Introduction to Computing, 3rd ed. 36 Operations i. ii. iii. iv. v. vi. See complete solution at text web site.

37 C++ An Introduction to Computing, 3rd ed. 37 Part of the Picture : Simulation Simulation Modeling a dynamic process Using the model to study process behavior Some deterministic processes can be modeled with equations Example: Exponential growth modeled by

38 C++ An Introduction to Computing, 3rd ed. 38 Simulation Many problems modeled using randomness Requires a random number generator subprogram Technically can be only pseudo-random Properties Initial seed value required to begin process Each random number used to compute next

39 C++ An Introduction to Computing, 3rd ed. 39 RandomInt Class Operations provided Construction – initialized object with a random number Generation – provides object with new random number Constructor RandomInt object_name (low, high); Generate a new random number object_name.generate();

40 C++ An Introduction to Computing, 3rd ed. 40 Modeling a Dice Roll To model roll of two dice Declare two objects RandomInt die1 (1,6), die2(1,6); Generate random values die1.generate(); die2.generate(); Add the two values for the roll int pair = die1 + die2; Note implementation Figure 5.2Figure 5.2 View sample runsample run

41 C++ An Introduction to Computing, 3rd ed. 41 Normal Distributions Normal distributions model many physical processes Note familiar bell shaped curve

42 C++ An Introduction to Computing, 3rd ed. 42 Normal Distributions Algorithm to generate standard normal distribution 1. Set sum = 0 2. Do the following 12 times 1.Generate random number, x from uniform distribution 2.Add x to sum 3. Calculate z = sum – 6 4. To generate random number y with mean μ and standard deviation σ, calculate

43 C++ An Introduction to Computing, 3rd ed. 43 OBJECTive Thinking: Instance Methods Review of class methods Accessor method – instance method which retrieves value of instance variable Mutator method – instance method that modifies value of instance variable Converter – instance method which returns different representation/type of object Utility – instance method used by other methods (avoids redundant coding)

44 C++ An Introduction to Computing, 3rd ed. 44 Accessor Methods Sample accessors for class Name Figure 5.3 Driver Figure 5.4Figure 5.4 Sample accessors for class Student Figure 5.5 Driver Figure 5.6Figure 5.6


Download ppt "Using Classes Chapter 5. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further software development using OCD. Introduce basic features of classes."

Similar presentations


Ads by Google