Upload
jolie
View
45
Download
0
Embed Size (px)
DESCRIPTION
Strings, Classes, and Working With Class Interfaces. CMPSC 122 Penn State University Prepared by Doug Hogan. Overview. String class Headers Creating strings Manipulating and comparing strings Motivation for Object Oriented Programming Strings as objects Terminology and theory - PowerPoint PPT Presentation
Citation preview
1
Strings, Classes, and Working With Class
InterfacesCMPSC 122
Penn State UniversityPrepared by Doug Hogan
2
Overview String class
Headers Creating strings Manipulating and comparing strings
Motivation for Object Oriented Programming Strings as objects Terminology and theory
Another custom class Objects vs. classes Access rights Using a class interface
3
The string type Alternative to character arrays
Hides many details Easier to manipulate
Required headers #include <string> using namespace std;
string is part of the C++ standard library
4
Declaring strings
Uninitialized: Like primitive data types
e.g. string myString; Can then use assignment operator
e.g. myString = “this is a string”; Initialized:
Use string keyword, name, and initial value in parentheses e.g. string myString(“a string”);
5
Input/Output
cin and cout cin stops at whitespace
getline can be used for reading in strings with spaces included: getline(stream, receivingString); example:
cout << “Enter a string”;getline(cin, str1);
6
Manipulating Characters
Exactly the same as with arrays of characters!
Use an index in brackets to get or manipulate that character. string myString(“a string”); cout << myString[0];
prints “a” myString[0] = “A”;
changes myString to “A string”
7
Exercises (you do on paper)
Create a string called testString that is initially “Welcome to CMPSC 122” string testString("Welcome to CMPSC 122");
Change the course number to 121 instead testString[19] = '1';
Output the string cout << testString;
8
Operators and strings The string class lets you use the following
operators: Assignment: = Comparison: >=, >, <, <= Equality: ==, != Concatenation: +
Example: if(string1 < string2){ cout << string1 << " is before " << string2 << endl;}
9
Problem
Suppose you have these declarations: string str1 = "I love "; string str2 = "computer programming!";
Create a string called str3 from these two strings that reads "I love computer programming!" string str3 = str1 + str2;
10
A bit of terminology before the fun part…
We’ll call string variables objects. We can operate on strings with
functions use dot notation
e.g. objectName.operation(); said to be sending a message to the
string object
11
length() message length( ) returns the length of the
string it’s called on ex:
string hello("Hello"); cout << hello.length() << endl;
prints 5 Don’t forget the parentheses!! Must give the string object, then the
dot operator!!
12
Practice
Given string noun; cin >> noun;
Output the length of noun. cout << noun.length();
13
find() message find( ) takes a string as an
argument returns the index where the argument
is found in the object it’s called on ex:
string hello("Hello"); cout << hello.find("ll") << endl;
prints 2 if the string isn’t found, find( )
returns -1
14
Substrings: substr() message
Takes two integer arguments: first is starting character second is length
returns a substring of the given length string hello("Hello World"); cout << hello.substr(6, 5); << endl;
prints “World” goes up to string’s length if 2nd argument
is too short
15
Problems
Given string s1("abcdefghi"); string s2(s1.substr(4, 3));
What is stored in s2? Answer: efg
Write a line of code to store the location of the letter “d” from s1 in the following integer: int d; Answer: d = s1.find("d");
16
Given string s("Any string");Give the result of each message or what is wrong with it.
length(s) s.length s(length) s.length() Find("Any")
s.find(” ") s.substr(2) s.substr(2, 5) s.substr("tri") s.find("tri")
Modified Self-Check 4-8 from: Mercer, Rick. Computing Fundamentals with C++. Wilsonville, OR: Franklin, 1999.
17
Given string s("Any string");Give the result of each message or what is wrong with it.
length(s) no dot notation length takes no
argument s.length
no parentheses s(length)
parentheses misplaced s.length()
10 Find("Any")
no object
s.find(" ") 3
s.substr(2) not enough arguments
s.substr(2, 5) y str
s.substr("tri") wrong arguments
s.find("tri") 5
Modified Self-Check 4-8 from: Mercer, Rick. Computing Fundamentals with C++. Wilsonville, OR: Franklin, 1999.
18
Motivation for classes
Object-Oriented Programming (OOP) Package together a set of related data
and operations (encapsulation) Define a class (abstract data type), or
a new data type with its operations One instance of a class is called an
object The data and operations of a class are
called its members. string is an example of a class
19
Access rights in OOP
Classes are similar to structs Add the notion of access rights
class member data and operations can be public – accessible to anyone private – accessible only to the object
usually data are private operations are public
20
An example of a class: bankAccount
Data: name balance
Operations: create an account withdraw deposit check balance
21
Problem
Write down an example of a bankAccount object.
22
Bank Account Objects Objects are instances of the class One class, many objects
namebalance
acct1
$500.00
Marge
namebalance
acct2
$123.45
Bart
namebalance
acct3
$20.00
Homer
23
Class Interface Starting point for working with
classes
Defines the class Defines the WHAT, not the HOW
24
So what does a class interface look like?#include <string> // string class definition
using namespace std; // so std:: isn’t needed
class bankAccount{
public:bankAccount();// POST: default bankAccount object constructed with name == “?” and balance == 0void withdraw(int amount);// PRE: amount in dollars and amount > $0// POST: amount has been subtracted from balancevoid deposit(int amount);// PRE: amount in dollars and amount > $0
// POST: amount had been added on to balancedouble getBalance();// POST: FCTVAL == balance
private:string name; // full name of account holderdouble balance; // how much in the acct, in dollars
};
necessary headers‘class’ keyword to signal a class definition
name of the class
declarations of the member functions of the class (public section)
declarations of the member data of the class (private section)
note the semicolon!!!
25
What do public and private mean?
Public can be accessed by any function in any class
Private can only be accessed by functions who are
members of the same class Observations
public member functions private data why?
abstraction and information hiding protect the data from accidental changes
26
Some more observations Data are declared, but not initialized Functions are declared, but not
implemented PRE- and POST- conditions are essential
27
So how do we use it? For now, we will be the client or
user.
Create a bankAccount using a special function called a constructor. The constructor we have: bankAccount();
Called in odd way… in the declaration: bankAccount myAcct;
28
So how do we use it? To “do stuff” to or with our object, we
need to send it messages. Use the dot notation we learned for strings. objectName.operation(parameters?) Why?
need to say WHICH object to send the message to Example
Given: bankAccount myAcct; To deposit $50, myAcct.deposit(50);
29
Time for you to think… Create two accounts. Deposit $100 in the first and $75 in
the second. Then withdraw $50 from both.
30
Time for you to think… Create two accounts.
bankAccount acct1; bankAccount acct2;
Deposit $100 in the first and $75 in the second. acct1.deposit(100); acct2.deposit(75);
Then withdraw $50 from both. acct1.withdraw(50); acct2.withdraw(50);
namebalance
acct1
$0.00
?
namebalance
acct2
$0.00
?
namebalance
acct1
$100.00
?
namebalance
acct2
$75.00
?
namebalance
acct1
$50.00
?
namebalance
acct2
$25.00
?
31
More thinking…
How can we print out how much money we have in each account? balance is private must send a message! cout << acct1.getBalance(); // displays 50 cout << acct2.getBalance(); // displays 25
Our bankAccount interface isn’t perfect… How could it be improved?
namebalance
acct1
$50.00
? namebalance
acct2
$25.00
?