SlideShare une entreprise Scribd logo
1  sur  34
Using Classes
1
Classes and Function Members —
An Introduction to
OOP (Object-Oriented Programming)
Chapter 7
The "++" in C++
Classes
The iostream library provides the objects
cin, cout and cerr. These objects were not
originally provided in C++, but were added
to the language using its class mechanism
— a major modification of C's struct.
This mechanism allows any programmer to
add new types to the language. They are
necessary to model real-world objects that have
multiple attributes; e.g.,
2
temperature.
An object is a program entity whose type is a
class. Their main difference from other things
we've been calling "program objects" is that in
addition to storing data values they also have
built-in operations for operating on this
data.
3
Classname identifier;
object
anObject
operations
data
Although objects can be processed by "shipping
them off" to functions for processing,
externalFunction(anObject)
they can also operate on themselves using their
built-in operations, which are functions. These
functions are called by means of the "push-button"
dot operator:
anObject.internalFunction(...)
We say that . sends a message to anObject.
4
anObject
operations
data
internalFunction(...)
I/O Classes
5
Bell Labs’ Jerry Schwarz used the class mechanism
to create:
• an istream class, to define the object cin; and
• an ostream class, to define cout and cerr.
The resulting I/O system was so powerful and yet
easy to use that it was incorporated into the
language.
We will study these classes and the operations they
provide later after we look at another class provided
in C++.
The String Class
C has a library of basic functions that can be used
to process strings, which are simply char arrays
(see slide #9).
C++ added a new string class that provides:
• an easy way to store strings, and
• a large assortment of useful built-in
string-processing operations.
To use the string type, we must
#include <string>
6
Lab 7
Read §7.4
carefully
Warning: #include <string>
NOT
#include <string.h>
which is C's string-processing library
<cstring>
Some string Operations
(others in §7.4)
Operation string function
read a word from input (e.g., cin) input >> str;
read an entire line from input getline(instream, str);
find the length of string str str.size()
check if str is empty str.empty()
access the char in str at index i str[i]
concatenate str1 and str2 str1 + str2
compare str1 and str2 str1 == str2
(or !=, <, >, <=, >=)
access a substring str str.substr(pos, numChars)
insert a substring into a str str.insert(pos, subStr);
remove a substring from str str.remove(pos, numChars);
find first occurrence of string aStr
in str starting at position pos str.find(aStr, pos)
find first occurrence of any char of str.find_first_of(aStr, pos)
string aStr in str starting at pos
Skip leading
white space;
read until next
white space;
leave it in
stream
Read all chars
up to but not
including the
next newline
character;
remove it
from stream
7
First one
used in Lab 7
Print out handy reference sheet in Lab 7
Constant string::npos is
returned for unsuccessful searches
Note that some string operations are "normal" functions:
getline(cin, aString);
Other string operations are internal agents — built-in function
members that determine how the object is to respond to
messages they receive. These messages are sent using the
("push button") dot operator.
aString.size();
For example, aString "knows" how big it is, so when it
receives the size() message via the dot operator, it responds
with the appropriate answer.
In a sense, class objects are "smarter" than regular char, int,
double, ... objects because they can do things for themselves.
8
The "I can do it myself"
principle of OOP
They are external agents that act on objects.
String Objects
Variables, such as string variables, whose data is stored
in an array (a sequence of items) are called
indexed variables because each individual item can be
accessed by attaching an index (also called a subscript),
enclosed in square brackets, to the variable's name: var[index].
string name = "John Q. Doe";
Using the subscript operator []to access individual chars:
o
J h n Q .
name
0 1 2 3 4 5 6
D o
7 8 9
e
10
char firstInitial = name[0];
9
// last name -> Roe
For example, suppose name is declared by
Note that indexes
are numbered
beginning with 0.
name's value is an array of 11 characters:
// firstInitial = 'J'
name[8] = 'R';
Dynamic string Objects
name = "Mary M. Smith"; // name.size() =
Objects of type string can grow and shrink as necessary
to store their contents (unlike C-style strings):
o
J h n Q .
name
0 1 2 3 4 5 6
D o
7 8 9
e
10
a
M r y M .
name
0 1 2 3 4 5 6
S m
7 8 9
i
10
t
11
h
12
string name = "John Q. Doe"; // name.size() =
More examples: myName.size()
string myName;
11
13
myName = "John Calvin";
myName = "Susie Doe";
0
11
9 10
Note: The diagram for the string object name on
the preceding slide is really not correct. It shows
only the data part of this object and not the built-in
operations. But to save space, we will usually show
only the string of characters that it stores.
11
name
o
J h n Q .
0 1 2 3 4 5 6
D o
7 8 9
e
10
A large number of built-in string operations like
those described on earlier slides — e.g.,
size() empty()
insert() find()
find_first_of() find_last_of()
. . .
Another C++ class you may find useful is for complex
numbers:
12
Another C++ Class (Template)
Mathematically: a + bi C++: complex<T>(a,b)
1.5 + 3.2i complex<double>(1.5, 3.2)
i complex<double>(0, 1)
Inputs Outputs
(1.5, 3.2) (1.5,3.2)
(0, 1) (0, 1)
3.14 (3.14,0)
complex<T>, where T may be
float, double, or long double.
13
Figure 7.2 Quadratic Equation Solver — Complex Roots
/* This program solves quadratic equations using the
quadratic formula.
Input: the three coefficients of a quadratic equation
Output: the complex roots of the equation.
-----------------------------------------------------------*/
#include <iostream> // cout, cin, <<, >>
#include <complex> // complex types
using namespace std;
int main()
{
complex<double> a, b, c;
cout << "Enter the coefficients of a quadratic equation: ";
cin >> a >> b >> c;
complex<double> discriminant = b*b - 4.0*a*c,
root1, root2;
root1 = (-b + sqrt(discriminant)) / (2.0*a);
root2 = (-b - sqrt(discriminant)) / (2.0*a);
cout << "Roots are " << root1 << " and " << root2 << endl;
}
14
Sample runs:
Enter the coefficients of a quadratic equation: 1 4 3
Roots are (-1,0) and (-3,0)
Enter the coefficients of a quadratic equation: 2 0 -8
Roots are (2,0) and (-2,0)
Enter the coefficients of a quadratic equation: 2 0 8
Roots are (0,2) and (-0,-2)
Enter the coefficients of a quadratic equation: 1 2 3
Roots are (-1,1.41421) and (-1,-1.41421)
Enter the coefficients of a quadratic equation: (1,2) (3,4) (5,6)
Roots are (-0.22822,0.63589) and (-1.97178,-0.23589)
The I/O Classes
15
As we noted earlier, C++ provides an istream class
for processing input and an ostream class for
processing output and that
• cin is an object of type istream
• cout and cerr are objects of type ostream
To use these classes effectively, you must be aware of
the large collections of operations provided by them
(although like the string class, it really isn't feasible
to memorize all of them and how they are used.)
Read § 7.3 carefully; note the diagrams of
streams; note how I/O actually takes place.
format manipulators
Some ostream Operations
ostream function Description
cout << expr Insert expr into cout
cout.put(ch); Tell cout, "Insert ch into yourself"
cout << flush Write contents of cout to screen
cout << endl Write a newline to cout and flush it
cout << fixed Display reals in fixed-point notation
cout << scientific Display reals in scientific notation
cout << showpoint Display decimal point and trailing zeros for
real whole numbers
cout << noshowpoint Hide decimal point and trailing zeros for
real whole numbers
Read §7.3
carefully
16




cout is
buffered;
cerr is
not.
= default
Once used, stay in effect
(except for setw())
More ostream Operations
ostream function Description
cout << showpos Display sign for positive values
cout << noshowpos Hide sign for positive values
cout << boolalpha Display true, false as "true", "false"
cout << noboolalpha Display true, false as 1, 0
cout << setprecision(n) Display n decimal places for reals
cout << setw(w) Display next value in field of width w
cout << left Left-justify subsequent values
cout << right Right-justify subsequent values
cout << setfill(ch) Fill leading/trailing blanks with ch
#include <iomanip> for these
Read §7.3
carefully
17


18
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n1 = 111, n2 = 22;
double d1 = 3.0 , d2 = 4.5678;
char c1 = 'A', c2 = 'B';
cout << "1. " << n1 << n2 << d1 << d2 << c1 << c2 << endl;
cout << "2. " << n1 << " " << n2 << " " << d1 << " " << d2
<< " "<< c1 << " " << c2 << endl;
cout << fixed << showpoint << setprecision(2);
cout << "3. " << n1 << " " << n2 << " " << d1 << " " << d2
<< " " << c1 << " " << c2 << endl;
cout << "4. " << setw(5) << n1 << " " << n2 << " "
<< setw(8) << d1 << " " << setw(2) << d2 << " "
<< c1 << " " << c2 << endl;
Output:
1. 1112234.5678AB
2. 111 22 3 4.5678 A B
3. 111 22 3.00 4.57 A B
4. 111 22 3.00 4.57 A B
Rounds
Expands if
width too small
------------------------------
------------------------------
------------------------------
------------------------------
Some istream Operations
istream function Description
cin >> var; Skip white space and extract
characters from cin up to the first one
that can't be in a value for var;
convert and store it in var.
cin.get(ch); Tell cin, "Put your next character;
(whitespace or not) into ch."
19
Tabs, spaces,
end-of-lines
Both are
used in
Lab 7
Examples (cont. from earlier):
cout << "> ";
cin >> n1 >> d1 >> n2 >> d2 >> c1 >> c2;
cout << "Output:n"
<< n1 << " " << n2 << " " << d1 << " " << d2 << " "
<< c1 << " " << c2 << endl;
20
Input/Output: cin:
> 1
2.2
3
4.4
A
B
Output:
1 3 2.20 4.40 A B
1 2 . 2 3 4 . 4 A B 





Input/Output: cin:
> 1 2.2 3 4.4 A B
Output:
1 3 2.20 4.40 A B
1 2 . 2 3 4 . 4 A B 
--------------------
--------------------
Same as before
21
Input/Output: cin:
> 12.2 34.4A5B
Output:
4 5 12.20 0.40 3 A
The character B is left in cin for the next input statement.
Input/Output: cin:
> 12.2 34.4AB
Output:
12 34 0.20 0.40 A B
cout << "> ";
cin >> n1 >> d1 >> n2 >> d2 >> c1 >> c2;
cout << "Output:n"
<< n1 << " " << n2 << " " << d1 << " " << d2 << " "
<< c1 << " " << c2 << endl;
cout << "> ";
cin >> d1 >> c1 >> n1 >> d2 >> c2 >> n2;
cout << "Output:n"
<< n1 << " " << n2 << " " << d1 << " " << d2 << " "
<< c1 << " " << c2 << endl;
1 2 . 2 3 4 . 4 A B 

1 2 . 2 3 4 . 4 A 5 B
--------------------
--------------------
22
for (int i = 1; i <= 5; i++)
{
cout << "> ";
cin >> d1 >> c1 >> n1 >> d2 >> c2 >> n2;
cout << "Output:n"
<< n1 << " " << n2 << " " << d1 << " " << d2 << " "
<< c1 << " " << c2 << endl;
}
In the last example, a character was left in cin for the next input
statement. To see how this can cause problems, suppose the
following code came after the preceding example:
> Output:
4 5 12.20 0.40 3 A
> Output:
4 5 12.20 0.40 3 A
> Output:
4 5 12.20 0.40 3 A
> Output:
4 5 12.20 0.40 3 A
> Output:
4 5 12.20 0.40 3 A
The following operations on
istreams like cin show how we
can recover from bad input.
When executed, the following output would be produced.
Execution would not pause to allow input of new values for the variables.
They retain their old values.
More istream Operations
istream function Description
cin.good() Ask cin, "Are you in good shape?"
cin.bad() Ask cin, "Is something wrong?"
cin.fail() Ask cin, "Did the last operation fail?"
cin.clear(); Tell cin, "Reset yourself to be good."
cin.ignore(n, ch); Tell cin, ignore the next n characters, or
until ch occurs, whichever comes first.
23



24
if (cin.fail()) // input failure?
{
cerr << "n** Non-numeric input!n";
cin.clear(); // reset all I/O status flags
cin.ignore(80, 'n'); // skip next 80 input chars
} // or until end-of-line char
else
break;
Example showing how to read a valid real number:
double number;
cout << "Enter a real number: ";
cin >> number;
while (true) // or for(;;)
{
}
Infinite Loop
Random Numbers
The text provides a RandomInt class.
Objects of this class are integers with "random"
values, which can be used to simulate all sorts of
"random" occurrences.
#include "RandomInt.h"
...
RandomInt die1(1,6), die2(1,6); // two dice
die1.generate(); // roll the dice
die2.generate();
cout << "dice roll = " // display results
<< die1 + die2 << endl;
25
Slides 25-30
are optional
More info in §7.5
RandomInt Objects
The range of random values is specified 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
26
RandomInt Operations
Operation RandomInt function
Display a RandomInt ostream << randInt
Declare a RandomInt RandomInt name;
Declare a RandomInt
within range first..last RandomInt name(first, last);
Generate new random value randInt.generate();
Generate new random value
from range first..last randInt.generate(first, last);
Add two RandomInt values randInt1 + randInt2
(also -, *, /)
Compare two RandomInt values randInt1 == randInt2
(also !=, <, >, <=, >=)
27
Figure 7.4 Simulate Shielding of a Nuclear Reactor
/* This program simulates particles entering the shield described in
the text and determines what percentage of them reaches the outside.
Input: thickness of the shield, limit on the number of direction
changes, number of neutrons, current direction a neutron
traveled
Output: the percentage of neutrons reaching the outside
--------------------------------------------------------------------*/
#include <iostream> // cin, cout, <<, >>
using namespace std;
#include "RandomInt.h" // random integer generator
int main()
{
int thickness,
collisionLimit,
neutrons;
cout << "nEnter the thickness of the shield, the limit on the n"
<< "number of collisions, and the number of neutrons:n";
cin >> thickness >> collisionLimit >> neutrons;
28
29
RandomInt direction(1,4);
int forward,
collisions,
oldDirection,
escaped = 0;
for (int i = 1; i <= neutrons; i++)
{
// Next neutron
forward = oldDirection = collisions = 0;
while (forward < thickness && forward >= 0 &&
collisions < collisionLimit)
{
direction.generate();
if (direction != oldDirection)
collisions++;
oldDirection = direction;
if (direction == 1)
forward++;
else if (direction == 2)
forward--;
}
if (forward >= thickness)
escaped++;
}
cout << 'n' << 100 * double(escaped) / double(neutrons)
<< "% of the particles escaped.n";
}
Sample runs:
Enter the thickness of the shield, the limit on the
number of collisions, and the number of neutrons:
1 1 100
26% of the particles escaped
Enter the thickness of the shield, the limit on the
number of collisions, and the number of neutrons:
100 5 1000
0% of the particles escaped
Enter the thickness of the shield, the limit on the
number of collisions, and the number of neutrons:
4 5 100
3% of the particles escaped
Enter the thickness of the shield, the limit on the
number of collisions, and the number of neutrons:
8 10 500
0.2% of the particles escaped 30
Well-designed classes provide a rich set of
operations that make them useful for many
problems.
Operations can be external (normal) functions to
which objects are passed for processing; or they
may be internal function members of the class.
Function members receive messages to class
objects and determine the response.
31
Some Final Notes about Classes
Read
To use a class effectively, you must know what
capabilities the class provides; and how to use
those capabilities.
32
• Be aware of the functionality a class provides
(but don’t memorize the nitty-gritty details).
• Know where (in a reference book) to look up
the operations a class supports.
• Then, when a problem involves an operation on
a class object, scan the list of operations
looking for one that you can use — don’t
reinvent the wheel!
Read
/* translate.cpp is an English-to-Pig-Latin translator.
==> PUT YOUR USUAL OPENING DOCUMENTATION HERE: NAME,
==> COURSE AND SECTION, DATE
Input: English sentences.
Precondition: Each sentence contains at least one word.
Output: The equivalent Pig-latin sentence.
---------------------------------------------------------------*/
#include <iostream> // cin, cout, <<, >>
#include <string> // class string
using namespace std;
//==> PUT YOUR PROTOTYPE OF FUNCTION englishToPigLatin() HERE
int main()
{
//==> PUT YOUR USUAL OPENING STATEMENT HERE TO OUTPUT-
//==> YOUR NAME, LAB #, COURSE AND SECTION INFO
cout << "Pig Latin translator.n";
string englishWord, pigLatinWord;
char separator;
33
cout << "nEnter an English sentence (xxx to stop):n";
cin >> englishWord;
while (englishWord != "xxx")
{
separator = ' ';
while (separator != 'n')
{
pigLatinWord = englishToPigLatin(englishWord);
cout << pigLatinWord;
cin.get(separator);
if (separator != 'n')
cout << ' ';
else
{
cout << endl;
cout << "nEnter next English sentence (xxx to stop):n";
}
cin >> englishWord;
}
}
}
//==> PUT YOUR DEFINITION OF FUNCTION englishToPigLatin() HERE
34
1 2

Contenu connexe

Similaire à Lecture 9_Classes.pptx

2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210Mahmoud Samir Fayed
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it outrajatryadav22
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingMeghaj Mallick
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202Mahmoud Samir Fayed
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structureSaad Gabr
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)SURBHI SAROHA
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 

Similaire à Lecture 9_Classes.pptx (20)

C++ practical
C++ practicalC++ practical
C++ practical
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
Array BPK 2
Array BPK 2Array BPK 2
Array BPK 2
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202
 
Bw14
Bw14Bw14
Bw14
 
STL in C++
STL in C++STL in C++
STL in C++
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec2
Lec2Lec2
Lec2
 
Lec2&3_DataStructure
Lec2&3_DataStructureLec2&3_DataStructure
Lec2&3_DataStructure
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec2
Lec2Lec2
Lec2
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 

Dernier

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 

Dernier (20)

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 

Lecture 9_Classes.pptx

  • 1. Using Classes 1 Classes and Function Members — An Introduction to OOP (Object-Oriented Programming) Chapter 7 The "++" in C++
  • 2. Classes The iostream library provides the objects cin, cout and cerr. These objects were not originally provided in C++, but were added to the language using its class mechanism — a major modification of C's struct. This mechanism allows any programmer to add new types to the language. They are necessary to model real-world objects that have multiple attributes; e.g., 2 temperature.
  • 3. An object is a program entity whose type is a class. Their main difference from other things we've been calling "program objects" is that in addition to storing data values they also have built-in operations for operating on this data. 3 Classname identifier; object anObject operations data
  • 4. Although objects can be processed by "shipping them off" to functions for processing, externalFunction(anObject) they can also operate on themselves using their built-in operations, which are functions. These functions are called by means of the "push-button" dot operator: anObject.internalFunction(...) We say that . sends a message to anObject. 4 anObject operations data internalFunction(...)
  • 5. I/O Classes 5 Bell Labs’ Jerry Schwarz used the class mechanism to create: • an istream class, to define the object cin; and • an ostream class, to define cout and cerr. The resulting I/O system was so powerful and yet easy to use that it was incorporated into the language. We will study these classes and the operations they provide later after we look at another class provided in C++.
  • 6. The String Class C has a library of basic functions that can be used to process strings, which are simply char arrays (see slide #9). C++ added a new string class that provides: • an easy way to store strings, and • a large assortment of useful built-in string-processing operations. To use the string type, we must #include <string> 6 Lab 7 Read §7.4 carefully Warning: #include <string> NOT #include <string.h> which is C's string-processing library <cstring>
  • 7. Some string Operations (others in §7.4) Operation string function read a word from input (e.g., cin) input >> str; read an entire line from input getline(instream, str); find the length of string str str.size() check if str is empty str.empty() access the char in str at index i str[i] concatenate str1 and str2 str1 + str2 compare str1 and str2 str1 == str2 (or !=, <, >, <=, >=) access a substring str str.substr(pos, numChars) insert a substring into a str str.insert(pos, subStr); remove a substring from str str.remove(pos, numChars); find first occurrence of string aStr in str starting at position pos str.find(aStr, pos) find first occurrence of any char of str.find_first_of(aStr, pos) string aStr in str starting at pos Skip leading white space; read until next white space; leave it in stream Read all chars up to but not including the next newline character; remove it from stream 7 First one used in Lab 7 Print out handy reference sheet in Lab 7 Constant string::npos is returned for unsuccessful searches
  • 8. Note that some string operations are "normal" functions: getline(cin, aString); Other string operations are internal agents — built-in function members that determine how the object is to respond to messages they receive. These messages are sent using the ("push button") dot operator. aString.size(); For example, aString "knows" how big it is, so when it receives the size() message via the dot operator, it responds with the appropriate answer. In a sense, class objects are "smarter" than regular char, int, double, ... objects because they can do things for themselves. 8 The "I can do it myself" principle of OOP They are external agents that act on objects.
  • 9. String Objects Variables, such as string variables, whose data is stored in an array (a sequence of items) are called indexed variables because each individual item can be accessed by attaching an index (also called a subscript), enclosed in square brackets, to the variable's name: var[index]. string name = "John Q. Doe"; Using the subscript operator []to access individual chars: o J h n Q . name 0 1 2 3 4 5 6 D o 7 8 9 e 10 char firstInitial = name[0]; 9 // last name -> Roe For example, suppose name is declared by Note that indexes are numbered beginning with 0. name's value is an array of 11 characters: // firstInitial = 'J' name[8] = 'R';
  • 10. Dynamic string Objects name = "Mary M. Smith"; // name.size() = Objects of type string can grow and shrink as necessary to store their contents (unlike C-style strings): o J h n Q . name 0 1 2 3 4 5 6 D o 7 8 9 e 10 a M r y M . name 0 1 2 3 4 5 6 S m 7 8 9 i 10 t 11 h 12 string name = "John Q. Doe"; // name.size() = More examples: myName.size() string myName; 11 13 myName = "John Calvin"; myName = "Susie Doe"; 0 11 9 10
  • 11. Note: The diagram for the string object name on the preceding slide is really not correct. It shows only the data part of this object and not the built-in operations. But to save space, we will usually show only the string of characters that it stores. 11 name o J h n Q . 0 1 2 3 4 5 6 D o 7 8 9 e 10 A large number of built-in string operations like those described on earlier slides — e.g., size() empty() insert() find() find_first_of() find_last_of() . . .
  • 12. Another C++ class you may find useful is for complex numbers: 12 Another C++ Class (Template) Mathematically: a + bi C++: complex<T>(a,b) 1.5 + 3.2i complex<double>(1.5, 3.2) i complex<double>(0, 1) Inputs Outputs (1.5, 3.2) (1.5,3.2) (0, 1) (0, 1) 3.14 (3.14,0) complex<T>, where T may be float, double, or long double.
  • 13. 13 Figure 7.2 Quadratic Equation Solver — Complex Roots /* This program solves quadratic equations using the quadratic formula. Input: the three coefficients of a quadratic equation Output: the complex roots of the equation. -----------------------------------------------------------*/ #include <iostream> // cout, cin, <<, >> #include <complex> // complex types using namespace std; int main() { complex<double> a, b, c; cout << "Enter the coefficients of a quadratic equation: "; cin >> a >> b >> c; complex<double> discriminant = b*b - 4.0*a*c, root1, root2; root1 = (-b + sqrt(discriminant)) / (2.0*a); root2 = (-b - sqrt(discriminant)) / (2.0*a); cout << "Roots are " << root1 << " and " << root2 << endl; }
  • 14. 14 Sample runs: Enter the coefficients of a quadratic equation: 1 4 3 Roots are (-1,0) and (-3,0) Enter the coefficients of a quadratic equation: 2 0 -8 Roots are (2,0) and (-2,0) Enter the coefficients of a quadratic equation: 2 0 8 Roots are (0,2) and (-0,-2) Enter the coefficients of a quadratic equation: 1 2 3 Roots are (-1,1.41421) and (-1,-1.41421) Enter the coefficients of a quadratic equation: (1,2) (3,4) (5,6) Roots are (-0.22822,0.63589) and (-1.97178,-0.23589)
  • 15. The I/O Classes 15 As we noted earlier, C++ provides an istream class for processing input and an ostream class for processing output and that • cin is an object of type istream • cout and cerr are objects of type ostream To use these classes effectively, you must be aware of the large collections of operations provided by them (although like the string class, it really isn't feasible to memorize all of them and how they are used.) Read § 7.3 carefully; note the diagrams of streams; note how I/O actually takes place.
  • 16. format manipulators Some ostream Operations ostream function Description cout << expr Insert expr into cout cout.put(ch); Tell cout, "Insert ch into yourself" cout << flush Write contents of cout to screen cout << endl Write a newline to cout and flush it cout << fixed Display reals in fixed-point notation cout << scientific Display reals in scientific notation cout << showpoint Display decimal point and trailing zeros for real whole numbers cout << noshowpoint Hide decimal point and trailing zeros for real whole numbers Read §7.3 carefully 16     cout is buffered; cerr is not. = default Once used, stay in effect (except for setw())
  • 17. More ostream Operations ostream function Description cout << showpos Display sign for positive values cout << noshowpos Hide sign for positive values cout << boolalpha Display true, false as "true", "false" cout << noboolalpha Display true, false as 1, 0 cout << setprecision(n) Display n decimal places for reals cout << setw(w) Display next value in field of width w cout << left Left-justify subsequent values cout << right Right-justify subsequent values cout << setfill(ch) Fill leading/trailing blanks with ch #include <iomanip> for these Read §7.3 carefully 17  
  • 18. 18 Example: #include <iostream> #include <iomanip> using namespace std; int main() { int n1 = 111, n2 = 22; double d1 = 3.0 , d2 = 4.5678; char c1 = 'A', c2 = 'B'; cout << "1. " << n1 << n2 << d1 << d2 << c1 << c2 << endl; cout << "2. " << n1 << " " << n2 << " " << d1 << " " << d2 << " "<< c1 << " " << c2 << endl; cout << fixed << showpoint << setprecision(2); cout << "3. " << n1 << " " << n2 << " " << d1 << " " << d2 << " " << c1 << " " << c2 << endl; cout << "4. " << setw(5) << n1 << " " << n2 << " " << setw(8) << d1 << " " << setw(2) << d2 << " " << c1 << " " << c2 << endl; Output: 1. 1112234.5678AB 2. 111 22 3 4.5678 A B 3. 111 22 3.00 4.57 A B 4. 111 22 3.00 4.57 A B Rounds Expands if width too small ------------------------------ ------------------------------ ------------------------------ ------------------------------
  • 19. Some istream Operations istream function Description cin >> var; Skip white space and extract characters from cin up to the first one that can't be in a value for var; convert and store it in var. cin.get(ch); Tell cin, "Put your next character; (whitespace or not) into ch." 19 Tabs, spaces, end-of-lines Both are used in Lab 7
  • 20. Examples (cont. from earlier): cout << "> "; cin >> n1 >> d1 >> n2 >> d2 >> c1 >> c2; cout << "Output:n" << n1 << " " << n2 << " " << d1 << " " << d2 << " " << c1 << " " << c2 << endl; 20 Input/Output: cin: > 1 2.2 3 4.4 A B Output: 1 3 2.20 4.40 A B 1 2 . 2 3 4 . 4 A B       Input/Output: cin: > 1 2.2 3 4.4 A B Output: 1 3 2.20 4.40 A B 1 2 . 2 3 4 . 4 A B  -------------------- -------------------- Same as before
  • 21. 21 Input/Output: cin: > 12.2 34.4A5B Output: 4 5 12.20 0.40 3 A The character B is left in cin for the next input statement. Input/Output: cin: > 12.2 34.4AB Output: 12 34 0.20 0.40 A B cout << "> "; cin >> n1 >> d1 >> n2 >> d2 >> c1 >> c2; cout << "Output:n" << n1 << " " << n2 << " " << d1 << " " << d2 << " " << c1 << " " << c2 << endl; cout << "> "; cin >> d1 >> c1 >> n1 >> d2 >> c2 >> n2; cout << "Output:n" << n1 << " " << n2 << " " << d1 << " " << d2 << " " << c1 << " " << c2 << endl; 1 2 . 2 3 4 . 4 A B   1 2 . 2 3 4 . 4 A 5 B -------------------- --------------------
  • 22. 22 for (int i = 1; i <= 5; i++) { cout << "> "; cin >> d1 >> c1 >> n1 >> d2 >> c2 >> n2; cout << "Output:n" << n1 << " " << n2 << " " << d1 << " " << d2 << " " << c1 << " " << c2 << endl; } In the last example, a character was left in cin for the next input statement. To see how this can cause problems, suppose the following code came after the preceding example: > Output: 4 5 12.20 0.40 3 A > Output: 4 5 12.20 0.40 3 A > Output: 4 5 12.20 0.40 3 A > Output: 4 5 12.20 0.40 3 A > Output: 4 5 12.20 0.40 3 A The following operations on istreams like cin show how we can recover from bad input. When executed, the following output would be produced. Execution would not pause to allow input of new values for the variables. They retain their old values.
  • 23. More istream Operations istream function Description cin.good() Ask cin, "Are you in good shape?" cin.bad() Ask cin, "Is something wrong?" cin.fail() Ask cin, "Did the last operation fail?" cin.clear(); Tell cin, "Reset yourself to be good." cin.ignore(n, ch); Tell cin, ignore the next n characters, or until ch occurs, whichever comes first. 23   
  • 24. 24 if (cin.fail()) // input failure? { cerr << "n** Non-numeric input!n"; cin.clear(); // reset all I/O status flags cin.ignore(80, 'n'); // skip next 80 input chars } // or until end-of-line char else break; Example showing how to read a valid real number: double number; cout << "Enter a real number: "; cin >> number; while (true) // or for(;;) { } Infinite Loop
  • 25. Random Numbers The text provides a RandomInt class. Objects of this class are integers with "random" values, which can be used to simulate all sorts of "random" occurrences. #include "RandomInt.h" ... RandomInt die1(1,6), die2(1,6); // two dice die1.generate(); // roll the dice die2.generate(); cout << "dice roll = " // display results << die1 + die2 << endl; 25 Slides 25-30 are optional More info in §7.5
  • 26. RandomInt Objects The range of random values is specified 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 26
  • 27. RandomInt Operations Operation RandomInt function Display a RandomInt ostream << randInt Declare a RandomInt RandomInt name; Declare a RandomInt within range first..last RandomInt name(first, last); Generate new random value randInt.generate(); Generate new random value from range first..last randInt.generate(first, last); Add two RandomInt values randInt1 + randInt2 (also -, *, /) Compare two RandomInt values randInt1 == randInt2 (also !=, <, >, <=, >=) 27
  • 28. Figure 7.4 Simulate Shielding of a Nuclear Reactor /* This program simulates particles entering the shield described in the text and determines what percentage of them reaches the outside. Input: thickness of the shield, limit on the number of direction changes, number of neutrons, current direction a neutron traveled Output: the percentage of neutrons reaching the outside --------------------------------------------------------------------*/ #include <iostream> // cin, cout, <<, >> using namespace std; #include "RandomInt.h" // random integer generator int main() { int thickness, collisionLimit, neutrons; cout << "nEnter the thickness of the shield, the limit on the n" << "number of collisions, and the number of neutrons:n"; cin >> thickness >> collisionLimit >> neutrons; 28
  • 29. 29 RandomInt direction(1,4); int forward, collisions, oldDirection, escaped = 0; for (int i = 1; i <= neutrons; i++) { // Next neutron forward = oldDirection = collisions = 0; while (forward < thickness && forward >= 0 && collisions < collisionLimit) { direction.generate(); if (direction != oldDirection) collisions++; oldDirection = direction; if (direction == 1) forward++; else if (direction == 2) forward--; } if (forward >= thickness) escaped++; } cout << 'n' << 100 * double(escaped) / double(neutrons) << "% of the particles escaped.n"; }
  • 30. Sample runs: Enter the thickness of the shield, the limit on the number of collisions, and the number of neutrons: 1 1 100 26% of the particles escaped Enter the thickness of the shield, the limit on the number of collisions, and the number of neutrons: 100 5 1000 0% of the particles escaped Enter the thickness of the shield, the limit on the number of collisions, and the number of neutrons: 4 5 100 3% of the particles escaped Enter the thickness of the shield, the limit on the number of collisions, and the number of neutrons: 8 10 500 0.2% of the particles escaped 30
  • 31. Well-designed classes provide a rich set of operations that make them useful for many problems. Operations can be external (normal) functions to which objects are passed for processing; or they may be internal function members of the class. Function members receive messages to class objects and determine the response. 31 Some Final Notes about Classes Read
  • 32. To use a class effectively, you must know what capabilities the class provides; and how to use those capabilities. 32 • Be aware of the functionality a class provides (but don’t memorize the nitty-gritty details). • Know where (in a reference book) to look up the operations a class supports. • Then, when a problem involves an operation on a class object, scan the list of operations looking for one that you can use — don’t reinvent the wheel! Read
  • 33. /* translate.cpp is an English-to-Pig-Latin translator. ==> PUT YOUR USUAL OPENING DOCUMENTATION HERE: NAME, ==> COURSE AND SECTION, DATE Input: English sentences. Precondition: Each sentence contains at least one word. Output: The equivalent Pig-latin sentence. ---------------------------------------------------------------*/ #include <iostream> // cin, cout, <<, >> #include <string> // class string using namespace std; //==> PUT YOUR PROTOTYPE OF FUNCTION englishToPigLatin() HERE int main() { //==> PUT YOUR USUAL OPENING STATEMENT HERE TO OUTPUT- //==> YOUR NAME, LAB #, COURSE AND SECTION INFO cout << "Pig Latin translator.n"; string englishWord, pigLatinWord; char separator; 33
  • 34. cout << "nEnter an English sentence (xxx to stop):n"; cin >> englishWord; while (englishWord != "xxx") { separator = ' '; while (separator != 'n') { pigLatinWord = englishToPigLatin(englishWord); cout << pigLatinWord; cin.get(separator); if (separator != 'n') cout << ' '; else { cout << endl; cout << "nEnter next English sentence (xxx to stop):n"; } cin >> englishWord; } } } //==> PUT YOUR DEFINITION OF FUNCTION englishToPigLatin() HERE 34 1 2