5
C++ A Beginner’s Guide by Herbert Schildt
The output produced by this program is shown here:
Minivan can carry 7 with a range of 336
Sportscar can carry 2 with a range of 168
As you can see, minivan’s data is completely separate from the data contained in sportscar. Figure 8-1
depicts this situation.
6
C++ A Beginner’s Guide by Herbert Schildt
1. A class can contain what two things?
2. What operator is used to access the members of a class through an object?
3. Each object has its own copies of the class’ _____________.
CRITICAL SKILL 8.3: Adding Member Functions to a Class
So far, Vehicle contains only data, but no functions. Although data-only classes are perfectly valid, most
classes will have function members. In general, member functions manipulate the data defined by the
class and, in many cases, provide access to that data. Typically, other parts of your program will interact
with a class through its functions.
To illustrate member functions, we will add one to the Vehicle class. Recall that main( ) in the preceding
examples computed the range of a vehicle by multiplying its fuel consumption rate by its fuel capacity.
While technically correct, this is not the best way to handle this computation. The calculation of a
vehicle’s range is something that is best handled by the
Vehicle class itself. The reason for this conclusion is easy to understand: The range of a vehicle is
dependent upon the capacity of the fuel tank and the rate of fuel consumption, and both of these
quantities are encapsulated by Vehicle. By adding a function to Vehicle that computes the range, you
are enhancing its object-oriented structure.
To add a function to Vehicle, specify its prototype within Vehicle’s declaration. For example, the
following version of Vehicle specifies a member function called range( ), which returns the range of the
vehicle:
7
C++ A Beginner’s Guide by Herbert Schildt
Because a member function, such as range( ), is prototyped within the class definition, it need not be
prototyped elsewhere.
To implement a member function, you must tell the compiler to which class the function belongs by
qualifying the function’s name with its class name. For example, here is one way to code the range( )
function:
// Implement the range member function. int Vehicle::range() {
return mpg * fuelcap; }
Notice the :: that separates the class name Vehicle from the function name range( ). The :: is called the
scope resolution operator. It links a class name with a member name in order to tell the compiler what
class the member belongs to. In this case, it links range( ) to the Vehicle class. In other words, :: states
that this range( ) is in Vehicle’s scope. Several different classes can use the same function names. The
compiler knows which function belongs to which class because of the scope resolution operator and the
class name.
The body of range( ) consists solely of this line:
return mpg * fuelcap;
This statement returns the range of the vehicle by multiplying fuelcap by mpg. Since each object of type
Vehicle has its own copy of fuelcap and mpg, when range( ) is called, the range computation uses the
calling object’s copies of those variables.
Inside range( ) the instance variables fuelcap and mpg are referred to directly, without preceding them
with an object name or the dot operator. When a member function uses an instance variable that is
defined by its class, it does so directly, without explicit reference to an object and without use of the dot
operator. This is easy to understand if you think about it. A member function is always invoked relative
to some object of its class. Once this invocation has occurred, the object is known. Thus, within a
member function, there is no need to specify the object a second time. This means that fuelcap and mpg
inside range( ) implicitly refer to the copies of those variables found in the object that invokes range( ).
Of course, code outside Vehicle must refer to fuelcap and mpg through an object and by using the dot
operator.
A member function must be called relative to a specific object. There are two ways that this can happen.
First, a member function can be called by code that is outside its class. In this case, you must use the
object’s name and the dot operator. For example, this calls range( ) on minivan:
8
C++ A Beginner’s Guide by Herbert Schildt
range = minivan.range();
The invocation minivan.range( ) causes range( ) to operate on minivan’s copy of the instance variables.
Thus, it returns the range for minivan.
The second way a member function can be called is from within another member function of the same
class. When one member function calls another member function of the same class, it can do so directly,
without using the dot operator. In this case, the compiler already knows which object is being operated
upon. It is only when a member function is called by code that does not belong to the class that the
object name and the dot operator must be used.
The program shown here puts together all the pieces and missing details, and illustrates the range( )
function:
9
C++ A Beginner’s Guide by Herbert Schildt
This program displays the following output:
Minivan can carry 7 with a range of 336
Sportscar can carry 2 with a range of 168
1. What is the :: operator called?
2. What does :: do?
3. If a member function is called from outside its class, it must be called through an object using
the dot operator. True or false?
Project 8-1 Creating a Help Class
If one were to try to summarize the essence of the class in one sentence, it might be this: A class
encapsulates functionality. Of course, sometimes the trick is knowing where one “functionality” ends
and another begins. As a general rule, you will want your classes to be the building blocks of your larger
application. To do this, each class must represent a single functional unit that performs clearly
delineated actions. Thus, you will want your classes to be as small as possible—but no smaller! That is,
classes that contain extraneous functionality confuse and destructure code, but classes that contain too
little functionality are fragmented. What is the balance? It is at this point that the science of
programming becomes the art of programming. Fortunately, most programmers find that this balancing
act becomes easier with experience.
To begin gaining that experience, you will convert the help system from Project 3-3 in Module 3 into a
Help class. Let’s examine why this is a good idea. First, the help system defines one logical unit. It simply
displays the syntax for the C++ control statements. Thus, its functionality is compact and well defined.
Second, putting help in a class is an esthetically pleasing approach. Whenever you want to offer the help
10
C++ A Beginner’s Guide by Herbert Schildt
system to a user, simply instantiate a help-system object. Finally, because help is encapsulated, it can be
upgraded or changed without causing unwanted side effects in the programs that use it.
Step by Step
1. Create a new file called HelpClass.cpp. To save you some typing, you might want to copy the file from
Project 3-3, Help3.cpp, into HelpClass.cpp.
2. To convert the help system into a class, you must first determine precisely what constitutes the help
system. For example, in Help3.cpp, there is code to display a menu, input the user’s choice, check for a
valid response, and display information about the item selected. The program also loops until q is
pressed. If you think about it, it is clear that the menu, the check for a valid response, and the display of
the information are integral to the help system. How user input is obtained, and whether repeated
requests should be processed, are not. Thus, you will create a class that displays the help information,
the help menu, and checks for a valid selection. These functions will be called helpon( ), showmenu(
),and isvalid( ), respectively.
3. Declare the Help class, as shown here:
Notice that this is a function-only class; no instance variables are needed. As explained, data-only and
code-only classes are perfectly valid. (Question 9 in the Mastery Check adds an instance variable to the
Help class.)
4. Create the helpon( ) function, as shown here:
11
C++ A Beginner’s Guide by Herbert Schildt
5. Create the showmenu( ) function:
12
C++ A Beginner’s Guide by Herbert Schildt
6. Create the isvalid( ) function, shown here:
7. Rewrite the main( ) function from Project 3-3 so that it uses the new Help class. The entire listing for
HelpClass.cpp is shown here:
13
C++ A Beginner’s Guide by Herbert Schildt
14
C++ A Beginner’s Guide by Herbert Schildt
When you try the program, you will find that it is functionally the same as in Module 3. The advantage to
this approach is that you now have a help system component that can be reused whenever it is needed.
CRITICAL SKILL 8.4: Constructors and Destructors
In the preceding examples, the instance variables of each Vehicle object had to be set manually by use
of a sequence of statements, such as:
Không có nhận xét nào:
Đăng nhận xét