3
Introduction to
Class and
Objects
O B J E C T I V E S
In this chapter you will learn:
■What class, objects, member functions and data
members are.
■How to define a class and u it to create an object.
拼音ei怎么读
■How to define member functions in a class to implement
the class’s behaviors.
■How to declare data members in a class to implement the
class’s attributes.
■How to call a member function of an object to make that
萝卜丁member function perform its task.
■The differences between data members of a class and
local variables of a function.
■How to u a constructor to ensure that an object’s data
is initialized when the object is created.
■How to engineer a class to parate its interface from its
implementation and encourage reu.
You will e something new.
Two things. And I call them
Thing One and Thing Two.
—Dr. Theodor Seuss Geil
Nothing can have value
without being an object of
utility.
—
Karl Marx
Your public rvants rve
you right.
—Adlai E. Stevenson
Knowing how to answer one
who speaks,
T o reply to one who nds a
message.
—Amenemope
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights rerved. This material is protected under all copyright laws as they currently exist.
奇志碰大兵
No portion of this material may be reproduced, in any form or by any means, without permission in writing from the publisher.
For the exclusive u of adopters of the book C++ How to Program, 5th Edition,
by Deitel and Deitel. ISBN 0-13-185757-6.
76Chapter 3Introduction to Class and Objects
Self-Review Exercis
3.1Fill in the blanks in each of the following:
a) A hou is to a blueprint as a(n) is to a class.
ANS:object.
b)Every class definition contains keyword followed immediately by the
class’s name.
ANS:class.
c) A class definition is typically stored in a file with the filename extension.
ANS:.h
d)Each parameter in a function header should specify both a(n) and a(n)
.
ANS:type, name.
e)When each object of a class maintains its own copy of an attribute, the variable that rep-
rents the attribute is also known as a(n) .
ANS:data member.
f)Keyword public is a(n) .
ANS:access specifier.
g)Return type indicates that a function will perform a task but will not re-
turn any information when it completes its task.
ANS:void.
h)Function from the <string> library reads characters until a newline char-
acter is encountered, then copies tho characters into the specified string.
ANS:getline.
i)When a member function is defined outside the class definition, the function header
must include the class name and the , followed by the function name to
“tie” the member function to the class definition.
ANS:binary scope resolution operator (::).
j)The source-code file and any other files that u a class can include the class’s header file via an preprocessor directive.
ANS:#include.
3.2State whether each of the following is true or fal. If fal, explain why.
a)By convention, function names begin with a capital letter and all subquent words in
the name begin with a capital letter.
ANS:Fal. By convention, function names begin with a lowerca first letter and all sub-quent words in the name begin with a capital first letter.
b)Empty parenthes following a function name in a function prototype indicate that the
function does not require any parameters to perform its task.
ANS:True.
不惑之年是多少岁c)Data members or member functions declared with access specifier private are accessi-
ble to member functions of the class in which they are declared.
ANS:True.
d)Variables declared in the body of a particular member function are known as data mem-
bers and can be ud in all member functions of the class.
ANS:Fal. Such variables are called local variables and can be ud only in the member function in which they are declared.
e)Every function’s body is delimited by left and right braces ({ and }).
ANS:True.
f)Any source-code file that contains int main() can be ud to execute a program.
ANS:True.
Exercis77
g)The types of arguments in a function call must match the types of the corresponding
parameters in the function prototype’s parameter list.
ANS:True.
3.3What is the difference between a local variable and a data member?
ANS:A local variable is declared in the body of a function and can be ud only from the point at which it is declared to the immediately following closing brace. A data mem-
ber is declared in a class definition, but not in the body of any of the class’s member
functions. Every object (instance) of a class has a parate copy of the class’s data
members. Also, data members are accessible to all member functions of the class. 3.4Explain the purpo of a function parameter. What is the difference between a parameter and an argument?
ANS:A parameter reprents additional information that a function requires to perform its task. Each parameter required by a function is specified in the function header. An
argument is the value supplied in the function call. When the function is called, the
argument value is pasd into the function parameter so that the function can per-
form its task.
Exercis
3.5Explain the difference between a function prototype and a function definition.
ANS:A function prototype tells the compiler the name of a function and the type of data returned by the function. A prototype also describes any additional data required by
the function to perform its task (i.e., the function’s parameters). A prototype does not
contain code to make the function perform the task—it merely outlines the function
so that the compiler can verify that programs call the function correctly. A function
谁笑到最后definition contains the actual code that executes to perform the function’s specified
task when the function is called. Parameter names are required in the function defi-
nition and optional in the function prototype.
3.6What is a default constructor? How are an object’s data members initialized if a class has only an implicitly defined default constructor?
ANS:A default constructor is the constructor that is called when a programmer creates an object with
out specifying any arguments to a constructor. The programmer can write
a default constructor that initializes data members any way the programmer choos.
The compiler provides a default constructor with no parameters in any class that does
not explicitly include a constructor. The default constructor provided by the compil-
er creates an object without assigning any initial values to the object’s data mem-
bers—data members must be initialized using the object’s member functions. Every
constructor implicitly calls the constructors of any data member objects before the
body of the class’s constructor executes.道教首创之地
3.7Explain the purpo of a data member.
ANS:A class provides a data member (or veral data members) when each object of the class must maintain data parately from all other objects of the class. For example, a
class called Account that reprents a bank account provides a data member to repre-
nt the balance of the account. Each Account object maintains its own balance, but
does not know the balances of the bank’s other accounts.
78Chapter 3Introduction to Class and Objects
3.8What is a header file? What is a source-code file? Discuss the purpo of each.
ANS:A header file typically contains a class definition, in which the member functions and data members of the class are declared (function prototypes are function declara-
tions). A source-code file is typically ud to provide the definitions of the member
functions declared in the class’s header file.
3.9Explain how a program could u class string without inrting a using declaration.
ANS:A program could create string variables without a using declaration if each occur-rence of the word string is prefixed by the namespace std and the binary scope res-
olution operator (::), as in std::string.
3.10Explain why a class might provide a t function and a get function for a data member.
ANS:A data member is typically declared private in a class so that only the member func-tions of the class in which the data member is declared can manipulate the variable.
A class typically provides a t function and a get function for a data member to allow
clients of the class to manipulate the data member in a controlled manner. A t func-
tion should validate the data it is tting to ensure that invalid data is not placed in
the object. A get function can return the value of a data member without allowing
clients to interact with the data member directly. In addition, t and get functions
hide the internal data reprentation. For example, a Time class might reprent the
time as the total number of conds since midnight. Such a class can provide member
functions getHour, getMinute and getSecond to calculate the hour, minute and c-
ond, respectively—even if the underlying data reprentation does not contain hour,
minute and cond data members. Similarly, a Time class could provide member func-
tions tHour, tMinute and tSecond to t the current hour, minute or cond
value. This would require each t function to perform calculations that update the
姑姑色data member containing the total number of conds since midnight.
3.11(Modifying Class GradeBook) Modify class GradeBook (Figs.3.11–3.12) as follows:
a)Include a cond string data member that reprents the cour instructor’s name.
b)Provide a t function to change the instructor’s name and a get function to retrieve it.
c)Modify the constructor to specify two parameters—one for the cour name and one
for the instructor’s name.
d)Modify member function displayMessage such that it first outputs the welcome mes-
sage and cour name, then outputs "This cour is prented by:" followed by the
instructor’s name.
U your modified class in a test program that demonstrates the class’s new capabilities.
ANS:
1// Exerci 3.11 Solution: GradeBook.h
2// Definition of GradeBook class that stores an instructor's name.
3#include <string> // program us C++ standard string class
4using std::string;
5
6// GradeBook class definition
7class GradeBook
8{
9public:
10// constructor initializes cour name and instructor name
11 GradeBook( string, string );
12void tCourName( string ); // function to t the cour name
13 string getCourName(); // function to retrieve the cour name
14void tInstructorName( string ); // function to t instructor name
Exercis79 15 string getInstructorName(); // function to retrieve instructor name 16void displayMessage(); // display welcome message and instructor name 17private:
18 string courName; // cour name for this GradeBook
19 string instructorName; // instructor name for this GradeBook
20}; // end class GradeBook
1// Exerci 3.11 Solution: GradeBook.cpp
2// Member-function definitions for class GradeBook.
3#include <iostream>
4using std::cout;
5using std::endl;
6
7// include definition of class GradeBook from GradeBook.h
8#include"GradeBook.h"
9
10// constructor initializes courName and instructorName
11// with strings supplied as arguments
12GradeBook::GradeBook( string cour, string instructor )
13{
14 tCourName( cour ); // initializes courName
15 tInstructorName( instructor ); // initialiZes instructorName
16} // end GradeBook constructor
17
18// function to t the cour name
19void GradeBook::tCourName( string name )
人参的最佳吃法20{
21 courName = name; // store the cour name
22} // end function tCourName
23
24// function to retrieve the cour name
25string GradeBook::getCourName()
26{
27return courName;
28} // end function getCourName
29
30// function to t the instructor name
31void GradeBook::tInstructorName( string name )
32{
33 instructorName = name; // store the instructor name
34} // end function tInstructorName
35
36// function to retrieve the instructor name
37string GradeBook::getInstructorName()
38{
39return instructorName;
40} // end function getInstructorName
41
42// display a welcome message and the instructor's name
43void GradeBook::displayMessage()
44{
45// display a welcome message containing the cour name
46 cout << "Welcome to the grade book for\n" << getCourName() << "!"
47 << endl;