1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by...

31
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan

Transcript of 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by...

Page 1: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

1

Strings, Classes, and Working With Class

InterfacesCMPSC 122

Penn State University

Prepared by Doug Hogan

Page 2: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared 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

Page 3: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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

Page 4: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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”);

Page 5: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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);

Page 6: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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”

Page 7: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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;

Page 8: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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;}

Page 9: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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;

Page 10: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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

Page 11: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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!!

Page 12: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

12

Practice

Given string noun; cin >> noun;

Output the length of noun. cout << noun.length();

Page 13: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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

Page 14: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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

Page 15: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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");

Page 16: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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.

Page 17: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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.

Page 18: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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

Page 19: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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

Page 20: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

20

An example of a class: bankAccount

Data: name balance

Operations: create an account withdraw deposit check balance

Page 21: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

21

Problem

Write down an example of a bankAccount object.

Page 22: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

22

Bank Account Objects

Objects are instances of the class One class, many objects

name

balance

acct1

$500.00

Marge

name

balance

acct2

$123.45

Bart

name

balance

acct3

$20.00

Homer

Page 23: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

23

Class Interface

Starting point for working with classes

Defines the class Defines the WHAT, not the HOW

Page 24: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

24

So what does a class interface look like?

#include <string> // string class definitionusing namespace std; // so std:: isn’t needed

class bankAccount{

public:bankAccount();// POST: default bankAccount object constructed with name == “?” and balance == 0

void withdraw(int amount);// PRE: amount in dollars and amount > $0// POST: amount has been subtracted from balance

void deposit(int amount);// PRE: amount in dollars and amount > $0

// POST: amount had been added on to balance

double 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!!!

Page 25: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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

Page 26: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

26

Some more observations

Data are declared, but not initialized Functions are declared, but not

implemented PRE- and POST- conditions are essential

Page 27: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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;

Page 28: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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);

Page 29: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

29

Time for you to think… Create two accounts. Deposit $100 in the first and $75 in

the second. Then withdraw $50 from both.

Page 30: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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);

name

balance

acct1

$0.00

?

name

balance

acct2

$0.00

?

name

balance

acct1

$100.00

?

name

balance

acct2

$75.00

?

name

balance

acct1

$50.00

?

name

balance

acct2

$25.00

?

Page 31: 1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

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?

name

balance

acct1

$50.00

? name

balance

acct2

$25.00

?