C - Program - 2e - Chapter07.pdf
(
667 KB
)
Pobierz
7
Classes and Objects
CHAPTER OBJECTIVES
Introduce the principles and definitions used in object-oriented
programming.
KEY TERMS AND CONCEPTS
access specifiers
array of objects
class
class constructor
class declaration
class definition
class destructor function
class members
instance of a class
method
object
obtaining computer system time
operator function
overloaded constructors
overloaded operators
private
public
Illustrate how classes incorporate data and functions.
Explain the relationship between the class declaration and
objects.
Demonstrate how a class declaration is written.
Show how the “world” may access public class members.
Present several simple program examples that illustrate the
mechanics of working with objects.
Describe the purpose of class constructor and destructor func-
tions, and illustrate how these functions are used in a program.
Illustrate how pointers and references to objects work.
KEYWORDS AND OPERATORS
class
operator
private
public
scoping operator
::
Who’s Job Is It?
H
ave you ever worked for a company where everyone had a specific job
title and responsibilities? If you were employed in the airline industry, you
know the various jobs include pilots, flight crew, mechanics, baggage
handlers, and reservation-staff, just to name a few. Perhaps you’ve spent time
working in a restaurant where the various job titles include managers, cooks,
wait-staff, host or hostess, bus-boys and girls. Now, if you were a waiter, what did
you do? You took customers’ orders, picked up, and served their food. You did-
n’t cook the food, nor did you order food from the supplier. If you were a bag-
gage handler for an airline, you didn’t fly the plane nor help customers make
reservations.
Are you asking yourself why we are off track talking about restaurants and
airlines when we should be learning how to write our own classes? Before I an-
swer that, let’s suppose you want to start your own business, say a bike messen-
ger service in the downtown area of a large city. You have to identify the various
jobs at your shop. What types of workers do you need? (Office manager, sched-
uler, messengers?) Then for each job, you need to identify the knowledge re-
quired to perform that job and its assigned tasks. As a programmer, writing
object-oriented programs, you have to examine all of the program goals and
identify the type of “workers” you need. Asking yourself what classes you need
and what each class is supposed to do is an important part of designing your
program. This is the same type of exercise that the new business owner must do
when identifying jobs and tasks. You decide what tasks are appropriate for your
new classes and what things each class will “need to know” in order to execute
specific tasks. Don’t forget, there may be C++ classes available for you to use
too. Isn’t that nice?
“Who’s job is it?” is an important question when dealing with classes and
objects. Keep that thought in mind as we move along here, and it will serve you
well as you design your own classes.
369
370
Chapter 7
❚
Classes and Objects
7.1
What Do We Know About Classes
and Objects?
Let’s review what we know about C++ classes before we jump into writing our
own. What classes have we used so far? Here is a short outline:
string
for handling text data
vector
for lists or groups of data, such as a list of strings or numbers
stringstream
for creating a formatted string
queue
models a line, (first in, first out) such as a bank line or a
play list for songs
ifstream
open and read data from a data file
ofstream
open and write data to a data file
For each of these classes, we include the appropriate library at the top of the file.
Inside a function we make an object that works for us. To use a class function, we
ask the object to perform a task by writing the object and a dot operator to access
the class’ function. The class is the job description for the object—it contains the
task list for the object.
The string class is handy for text data. We assign text into a string. The string
class’ “job description” gives us (among other things) the ability to assign, deter-
mine length, and find a substring in the string.
string sText;
//make a string object named sText
sText = "C++ classes are fun!";
//use = to assign
int length = sText.size();
//size() gives us length
int where = sText.find("fun");
//find() searches for us
We used the vector class in Chapter 3’s Program 3-18 when we searched for a
woman’s name. We stored the name and origin data in two separate vectors. To use
a vector object, we tell the object what type of data it will contain. We add items to
the vector using the
push_back()
function. We ask the vector how many items are
in the list with the
size()
function. The
at()
returns the item given an integer
index. Here are a few lines of code using a vector object:
vector <string> vNames;
//make a vector object, vNames
vNames.push_back("Mary");
//load names using push_back()
vNames.push_back("Carol");
vNames.push_back("Elizabeth");
int number = vNames.size();
//size() tells us how many names are
stored
cout << vNames.at(0);
//at() returns the first name
Our C++ Bank program in Chapter 5 (Program 5-8) incorporated a queue object.
Do you remember how to make and use a queue? We include the library, make an
object, then have the object perform tasks for us. The task list is defined in the
class. (Same song, different verse, right?) Here we make a
bankLine
queue object
371
Section 7.2
Writing Our Own Classes
❚
for customers (string objects), put three in the line, then serve and remove the
first one.
queue <string> bankLine;
//make a queue object bankLine
bankLine.push("Richard");
//add to the end of the line
using push()
bankLine.push("Roberto");
bankLine.push("Kristy");
cout << "Serving " << bankLine.front(); //front() returns the first name
bankLine.pop();
//remove the first element from
the line
If you haven’t discovered Appendix G, “Partial C++ Class Reference,” now is
the perfect time for you to look at this appendix. Here you can scan through a par-
tial listing of the string, vector, and queue class functions—in essence, these func-
tions show you their job descriptions. The designers of these C++ classes thought
about the class tasks when they wrote the class specifications. We’ll be doing the
same in this chapter.
7.2
Writing Our Own Classes
Hand-Waving Example: Our Date Class
No time like the present to design our own class. Let’s talk through a simple exam-
ple instead of getting bogged down with object-oriented principles, terminology,
and C++ syntax. The time to worry about semi-colons and braces will come soon
enough. For now, let’s pick an easy class and walk through its design. In this discus-
sion, we’ll layout the features for a Date class. After we design it, we’ll write it in
C++ code, and see how it works. It will then be ready for us to use throughout these
last two chapters.
What is the date today? If you’re like most of us, you’ll have to stop a minute
and think—unless it is an important date like your birthday! Now, did you think of
today’s date in terms of a month name, day, and year, or as three integers? The
exact form doesn’t matter—what does matter is that you know that the date data is
represented using three integers, or two integers and a string. A date can be de-
scribed using many formats. Here are a few ways to write the same date:
March, 14, 2007
Mar. 14, 2007
14-Mar-2007
14/3/2007
3/14/2007
03/14/07
14-March-2007
14/3/07
Regardless of the format, we have four pieces of data with the date, i.e., the month,
day, year (integers), and month name (string). What other information might you
need when talking about a date? You may need to know if your date is a leap year.
The year 2007 is not a leap year. A useful date value to know is what day of the year it
is. January 1 is the first day of the year. February 1 is the 32
nd
day of the year. Non-leap
years contain 365 days. Leap years contain an extra day: February, the 29
th
.Therefore,
in a non-leap year March 14 is the 73
rd
day of the year (obtained by adding
). One last feature of our customized Date class is that it will have a
31 + 28 + 14
372
Chapter 7
❚
Classes and Objects
You, the programmer
Date object
contains information
for one Date.
Date object
month =3
day = 14
year = 2007
day of the year = 73
leap year = false
description = Jason's Birthday
Date data
What can you ask the
Date object?
What month are you?
What day are you?
What year are you?
What day of year are you?
Give me a formatted
string discribing
yourself
Are you a leap year?
Figure 7-1
Information available from our date object.
string variable to hold a description so that it “knows” what the date represents—such
as “Jason’s Birthday”, “first day of school”, or “driver’s license expiration”.
When you write a class, you must think about the type of tasks (jobs) the
class objects will do for you. Our Date class holds date information for us, so what
would you like your Date object to do for you? Obviously, our Date object tell us
the month, day, year, and day of the year. It would be nice if it gave us a formatted
string of itself—such as “Jason’s Birthday: March 14, 2007”, as well as be able to
tell us if it is a leap year. Look at Figure 7-1 and see all the questions that our pro-
grammer can ask our Date object.
If you look at our Date object in Figure 7-1, it contains data for Jason’s Birth-
day. How did the data get into the Date object? There are a few ways to set the
Date object’s data. Let’s look at one way here. We need to be able to tell the Date
object what date it is holding and its description. Let’s allow our programmer to
pass three integers and one string into the Date object. This means we can change
the date information in our object anytime we wish. Let’s set our Date object data
to 7/30/2004, with “Ryan’s Birthday”. Figure 7-2 shows this. (Wait! Who’s job is it to
determine the day of the year? What about that pesky leap year?)
As class designers we must think about what happens when our object is con-
structed. We have to be sure that the class data in the object are initialized to
Plik z chomika:
Januszek66
Inne pliki z tego folderu:
Back Seat_ A Mumbai Tale - Aditya Kripalani.mobi
(755 KB)
Brief Wondrous Life of Oscar Wao, The - Junot Diaz.opf
(3 KB)
Don't Make Me Think, Revisited_ - Steve Krug.mobi
(9256 KB)
M. T. Anderson - Norumbegan 03 - The Empire of Gut and Bone # (v5.0).epub
(2209 KB)
M. T. Anderson - Norumbegan 02 - The Suburb Beyond the Stars # (v5.0).epub
(2105 KB)
Inne foldery tego chomika:
Dokumenty
Galeria
LUDLUM ROBERT
Midi - Kar
Mszał Rzymski PL
Zgłoś jeśli
naruszono regulamin