22
Using Classes Using Classes Classes and Function Members Classes and Function Members

Using Classes Classes and Function Members. Review We’ve seen that the iostream library provides the objects cin, cout and cerr: These objects were not

Embed Size (px)

Citation preview

Using ClassesUsing Classes

Classes and Function MembersClasses and Function Members

ReviewReview

We’ve seen that the iostream library We’ve seen that the iostream library provides the objects provides the objects cincin, , coutcout and and cerrcerr::

These objects were not originally provided These objects were not originally provided in C++, but were added to the language in C++, but were added to the language using its using its class mechanismclass mechanism..

ClassesClassesThe C++ class mechanism allows a user to The C++ class mechanism allows a user to

add new types to the language.add new types to the language.

Bell Labs’ Jerry Schwarz used this to create:Bell Labs’ Jerry Schwarz used this to create:

• an istream class, to define the object an istream class, to define the object cincin; ; andand

• an ostream class, to define an ostream class, to define coutcout and and cerrcerr..

The resulting I/O system was so elegant, The resulting I/O system was so elegant, it was incorporated into the language.it was incorporated into the language.

Classes (ii)Classes (ii)Another class that was added ‘after the Another class that was added ‘after the

fact’ is the string class, which provides a fact’ is the string class, which provides a convenient way to store and operate on convenient way to store and operate on sequences of characters.sequences of characters.

The string library provides the type string, The string library provides the type string, plus an assortment of useful string-plus an assortment of useful string-processing operations.processing operations.

String ObjectsString Objects

Objects of type Objects of type string are are indexed variablesindexed variables, , meaning that each character in the variable meaning that each character in the variable can be accessed via an index or subscript:can be accessed via an index or subscript:

string name = “John Q. Doe”;

Use the Use the subscript operatorsubscript operator to access individual chars: to access individual chars:

oJ h n Q .name0 1 2 3 4 5 6

D o7 8 9

e10

char firstInitial = name[0]; // firstInitial == ‘J’

Dynamic string ObjectsDynamic string Objects

name = “Philleas Fogg”; // name.size() == 13

Objects of type Objects of type string can grow and shrink as can grow and shrink as necessary to store their contents:necessary to store their contents:

oJ h n Q .name0 1 2 3 4 5 6

D o7 8 9

e10

hP i l l e aname0 1 2 3 4 5 6

s F7 8 9

o10

g11

g12

string name = “John Q. Doe”; // name.size() == 11

Some string OperationsSome string OperationsOperation string functionread a word from an istream read a word from an istream istreamistream >> >> strstr;;read a line from an istream getline(read a line from an istream getline(istreamistream, , strstr););find the length of the string find the length of the string strstr.size().size()find if a string is empty find if a string is empty strstr.empty().empty()access the char at index access the char at index ii strstr[[ii]]concatenate two strings concatenate two strings str1str1 + + str2str2access a substring of a string access a substring of a string strstr.substr(.substr(PosPos, , NumCharsNumChars))insert a substring into a string str.insert(insert a substring into a string str.insert(PosPos, , SubStrSubStr););remove a substring str.remove(remove a substring str.remove(PosPos, , NumCharsNumChars););find a substring in a string find a substring in a string strstr.find(.find(PatternPattern, , StartPosStartPos) ) compare two strings compare two strings str1str1 == == str2str2 (or !=, <, >, <=, >=)(or !=, <, >, <=, >=). . .. . .

DiscussionDiscussion

Some string operations are “normal” functions:Some string operations are “normal” functions:

getline(cin, aString);

Other string operations are Other string operations are function membersfunction members::

aString.size();

Function members are “messages” that class objects Function members are “messages” that class objects “understand” and to which they respond...“understand” and to which they respond...

For example, For example, aString “knows” how big it is, so “knows” how big it is, so when it receives the when it receives the size() message, it message, it responds with the appropriate answer.responds with the appropriate answer.

Function MembersFunction Members

Where a “normal” function is an external agent Where a “normal” function is an external agent that acts upon an object, a that acts upon an object, a function memberfunction member is is a message that elicits an internal response a message that elicits an internal response from the object receiving it.from the object receiving it.

Examples:Examples:getline(cin, aString); // getline() acts on aString

if (aString.empty()) // ask aString, “are you empty?”

if (cin.good()) // ask cin, “are you good?”

In this sense, class objects are “more intelligent” In this sense, class objects are “more intelligent” than regular char, int, double, ... objects. than regular char, int, double, ... objects.

ClassesClasses

Most classes provide a rich set of operations Most classes provide a rich set of operations that can be used to manipulate objects of the that can be used to manipulate objects of the class.class.

To use a class effectively, you must know what To use a class effectively, you must know what kinds of functions (“normal” and member) are kinds of functions (“normal” and member) are available to operate on objects of that class.available to operate on objects of that class.

Otherwise, you risk spending much of your time Otherwise, you risk spending much of your time “reinventing the wheel.”“reinventing the wheel.”

ExampleExample

Suppose a problem requires me to find the Suppose a problem requires me to find the position of a particular character within a string.position of a particular character within a string.

I can either write/call my own function to do so... I can either write/call my own function to do so...

int PositionOf(char ch; string str){ for (int i = 0; i < str.size(); i++) if (str[i] == ch) return i;

return -1;}

...

int pos = PositionOf(myChar, aString);

Example (ii)Example (ii)... or I can ask aString to locate myChar for me, using the string ... or I can ask aString to locate myChar for me, using the string

function member named find():function member named find():

int pos = aString.find(myChar, 0);

Which is less work?Which is less work?

• Writing your own is more work to code, test and Writing your own is more work to code, test and debug, and the result is less flexible than find(). debug, and the result is less flexible than find().

• Using find() requires awareness (i) that the Using find() requires awareness (i) that the function member exists, and (ii) of how to use it.function member exists, and (ii) of how to use it.

DiscussionDiscussion

Be aware of the functionality a class Be aware of the functionality a class provides (but don’t memorize the nitty-provides (but don’t memorize the nitty-gritty details).gritty details).

Know where (in a reference book) to look Know where (in a reference book) to look up the operations a class supports.up the operations a class supports.

Then, when a problem involves an Then, when a problem involves an operation on a class object, scan the list operation on a class object, scan the list of operations looking for one that you can of operations looking for one that you can use -- don’t reinvent the wheel!use -- don’t reinvent the wheel!

ExampleExample

The text provides a RandomInt class.The text provides a RandomInt class.

Objects of this class are integers with “random” Objects of this class are integers with “random” values, which can be used to simulate all sorts of values, which can be used to simulate all sorts of “random” occurrences.“random” occurrences.

#include “RandomInt.h”...RandomInt die1(1,6), die2(1,6); // two dice

die1.Generate(); die2.Generate() // roll the dice

cout << “dice roll = “ // display results << die1 + die2 << endl;

RandomInt ObjectsRandomInt Objects

The range of random values is specified The range of random values is specified when an object is declared:when an object is declared:

#include “RandomInt.h”...const int HEADS = 0, TAILS = 1;

RandomInt coin(HEADS,TAILS);

coin.Generate(); // flip coin

cout << coin << endl; // display result

RandomInt OperationsRandomInt OperationsOperation RandomInt function

Display a RandomInt Display a RandomInt ostreamostream << << randIntrandInt

Declare a RandomInt RandomIntDeclare a RandomInt RandomInt name name;;

Declare a RandomInt within Declare a RandomInt within rangerange first..last first..last RandomIntRandomInt name name((first, lastfirst, last););

Generate new random value Generate new random value randIntrandInt.Generate();.Generate();

Generate new random value from Generate new random value from range range first..lastfirst..last randIntrandInt.Generate(.Generate(firstfirst, , lastlast););

Add two RandomInt values Add two RandomInt values randInt1randInt1 + + randInt2 randInt2 (also -, *, /)(also -, *, /)

Compare two RandomInt values Compare two RandomInt values randInt1randInt1 == == randInt2 randInt2 (also !=, <, >, <=, >=)(also !=, <, >, <=, >=)

Sample ProgramSample Program#include <iostream> // cin, cout#include <iostream> // cin, coutusing namespace std;using namespace std;#include “RandomInt.h” // RandomInt class // RandomInt classint main()int main(){{ const int HEADS = 0, TAILS = 1; // for readabilityconst int HEADS = 0, TAILS = 1; // for readability RandomInt coin(HEADS, TAILS); // model a coin // model a coin int numHeads = 0, numTails = 0; // countersint numHeads = 0, numTails = 0; // counters for (int i = 1; i <= 10000; i++) // loop 10,000 timesfor (int i = 1; i <= 10000; i++) // loop 10,000 times {{ coin.Generate(); // flip coin // flip coin if (if (coin == HEADS) // count) // count numHeads++; // headsnumHeads++; // heads else // vs. tailselse // vs. tails numTails++;numTails++; }} cout << “\nIn 10,000 tosses of a coin,\n”cout << “\nIn 10,000 tosses of a coin,\n” << “ heads occurred “ << numHeads << “ times\n”<< “ heads occurred “ << numHeads << “ times\n” << “ and tails occurred << numTails << “ times”<< “ and tails occurred << numTails << “ times” << endl;<< endl;}}

Other ClassesOther Classes

As mentioned earlier, cin and cout are As mentioned earlier, cin and cout are objects of the istream and ostream objects of the istream and ostream classes, respectively.classes, respectively.

To use these classes effectively, you To use these classes effectively, you must be aware of the range operations must be aware of the range operations available for them...available for them...

Some istream OperationsSome istream Operationsistream function Description

cin >> cin >> chch; Extract next non-whitespace character ; Extract next non-whitespace character

from cin and store it in from cin and store it in chch..

cin.get(cin.get(chch); Tell cin, “Put your next character); Tell cin, “Put your next character (whitespace or not) into (whitespace or not) into chch.”.”

cin.good() Ask cin, “Are you in good shape?”cin.good() Ask cin, “Are you in good shape?”

cin.bad() Ask cin, “Is something wrong?"cin.bad() Ask cin, “Is something wrong?"

cin.fail() Ask cin, “Did the last operation fail?”cin.fail() Ask cin, “Did the last operation fail?”

cin.clear(); Tell cin, “Reset yourself to be good.”cin.clear(); Tell cin, “Reset yourself to be good.”

cin.ignore(cin.ignore(nn, , chch); Tell cin, ignore the next ); Tell cin, ignore the next nn characters, characters, or until or until chch occurs, whichever comes first. occurs, whichever comes first.

Some ostream OperationsSome ostream Operationsostream function Description

cout >> cout >> exprexpr Insert Insert exprexpr into cout. into cout.

cout.put(cout.put(chch); Tell cin, “Insert ); Tell cin, “Insert chch into yourself.” into yourself.”

cout << flush Write contents of cout to screen.cout << flush Write contents of cout to screen.

cout << endl Write a newline to cout and flush it.cout << endl Write a newline to cout and flush it.

cout << fixed Display reals in fixed-point notation.cout << fixed Display reals in fixed-point notation.

cout << scientific Display reals in scientific notation.cout << scientific Display reals in scientific notation.

cout << showpoint Display decimal point and trailing zeroscout << showpoint Display decimal point and trailing zeros for real whole numbers.for real whole numbers.

cout << noshowpoint Hide decimal point and trailing zeroscout << noshowpoint Hide decimal point and trailing zeros for real whole numbers.for real whole numbers.

More ostream OperationsMore ostream Operationsostream function Description

cout << showpos Display sign for positive values.cout << showpos Display sign for positive values.

cout << noshowpos Hide sign for positive values.cout << noshowpos Hide sign for positive values.

cout << boolalpha Display true, false as “true”, “false”.cout << boolalpha Display true, false as “true”, “false”.

cout << noboolalpha Display true, false as 1, 0.cout << noboolalpha Display true, false as 1, 0.

cout << setprecision(cout << setprecision(nn) Display ) Display nn decimal places for reals. decimal places for reals.

cout << setw(cout << setw(ww) Display next value in field width ) Display next value in field width ww..

cout << left Left-justify subsequent values.cout << left Left-justify subsequent values.

cout << right Right-justify subsequent values.cout << right Right-justify subsequent values.

cout << setfill(cout << setfill(chch) Fill leading/trailing blanks with ) Fill leading/trailing blanks with ch.ch.

SummarySummary

Well-designed classes provide a rich set of Well-designed classes provide a rich set of operations that make them useful for many operations that make them useful for many problems.problems.

Operations can be external (normal functions), Operations can be external (normal functions), or internal (function members) to the class.or internal (function members) to the class.

Function members act as Function members act as messagesmessages to class objects. to class objects.

To use a class effectively, you must know To use a class effectively, you must know

• what capabilities the class provides; andwhat capabilities the class provides; and

• how to use those capabilities.how to use those capabilities.