⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chap05.htm

📁 Since the field of object oriented programming is probably new to you, you will find that there is a
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<HTML>
<HEAD>
   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
   <META NAME="Author" CONTENT="Gordon Dodrill">
   <META NAME="GENERATOR" CONTENT="Mozilla/4.04 [en] (Win95; I) [Netscape]">
   <TITLE>C++ Tutorial - Chapter 5</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<B>C++ Tutorial - Chapter 5</B>

<P><B><FONT SIZE=+3>E</FONT><FONT SIZE=+2>NCAPSULATION</FONT></B>

<P>As mentioned in Chapter 1, object oriented programming will seem very
unnatural to a programmer with a lot of procedural programming experience.
This chapter is the beginning of the definition of object oriented programming,
and we will study the topic of encapsulation which is a "divide and conquer"
technique. As we stated earlier, there are a lot of new terms used with
object oriented programming. Don't be intimidated by the new terminology,
we will study the terms one at a time in a meaningful order.

<P>Encapsulation is the process of forming objects which we will discuss
throughout this chapter. An encapsulated object is often called an abstract
data type and it is what object oriented programming is all about. Without
encapsulation, which involves the use of one or more classes, there is
no object oriented programming. Of course there are other topics concerning
object oriented programming, but this is the cornerstone.

<P><B>WHY BOTHER WITH ENCAPSULATION?</B>

<P>We need encapsulation because we are human, and humans make errors.
When we properly encapsulate some code, we actually build an impenetrable
wall to protect the contained code from accidental corruption due to the
silly little errors that we are all prone to make. We also tend to isolate
errors to small sections of code to make them easier to find and fix. We
will have a lot more to say about the benefits of encapsulation as we progress
through the tutorial.

<P><B>NO INFORMATION HIDING</B>

<P>Example program ------> <B><A HREF="OPEN.CPP">OPEN.CPP</A></B>

<P>The program named OPEN.CPP is a really stupid program because it does
next to nothing, but it will be the beginning point for our discussion
of encapsulation, otherwise known as information hiding. Information hiding
is an important part of object oriented programming and you should have
a good grasp of what it is by the time we finish this chapter.

<P>A very simple structure is defined in lines 4 through 7 which contains
a single <B>int </B>type variable within the structure. This is sort of
a silly thing to do, but it will illustrate the problem we wish to overcome
in this chapter. Three variables are declared in line 11, each of which
contains a single <B>int </B>type variable and each of the three variables
are available for use anywhere within the <B>main()</B> function. Each
variable can be assigned, incremented, read, modified, or have any number
of operations performed on it. A few of the operations are illustrated
in lines 14 through 22 and should be self explanatory to anyone with a
little experience with the C programming language.

<P><IMG SRC="CPP0501.GIF" HSPACE=20 VSPACE=20 BORDER=0 HEIGHT=151 WIDTH=354>
<BR>An isolated local variable named <B>piggy </B>is declared and used
in the same section of code to illustrate that there is nothing magic about
this code. Figure 5-1 is a graphical representation of the data space after
execution of line 17.

<P>Study this simple program carefully because it is the basis for beginning
our study of encapsulation. Be sure to compile and execute this program,
then we will go on to the next example program where we will see our first
example of real information hiding.

<P><B>INFORMATION HIDING</B>

<P>Example program ------> <B><A HREF="CLAS.CPP">CLAS.CPP</A></B>

<P>Examine the program named CLAS.CPP for our first example of a program
with a little information hiding contained in it. This program is identical
to the last one except for the way it does a few of its operations. We
will take the differences one at a time and explain what is happening.
Keep in mind that this is a trivial program and the safeguards built into
it are not needed for such a simple program but are used here to illustrate
how to use these techniques in a larger much more complicated program.

<P>The first difference is that we have a <B>class </B>instead of a structure
beginning in line 4 of this program. The only difference between a class
and a structure is that a class begins with a private section whereas a
structure begins with a public section. The keyword <B>class </B>is used
to declare a class as illustrated here.

<P>The class named <B>one_datum</B> is composed of the single variable
named <B>data_store</B> and two functions, one named <B>set()</B> and the
other named <B>get_value()</B>. A more complete definition of a class is
a group of variables, and one or more functions that can operate on that
data. Stay with us, we will tie this all together in a meaningful and useful
way very soon.

<P><B>WHAT IS A PRIVATE SECTION?</B>

<P>All data at the beginning of a class defaults to private. Therefore,
the data at the beginning of the class cannot be accessed outside of the
class, it is hidden from any outside access. Therefore, the variable named
<B>data_store</B> which is a part of the object (an object will be defined
completely later) named <B>dog1 </B>defined in line 24, is not available
for use anywhere in the <B>main()</B> program. It is as if we have built
a "brick wall" around the variables to protect them from accidental corruption
by outside programming influences. It seems a little dumb to define a variable
in the<B> main()</B> program that we cannot use, but that is exactly what
we did.

<P><IMG SRC="CPP0502.GIF" HSPACE=20 VSPACE=20 BORDER=0 HEIGHT=118 WIDTH=213>
<BR>Figure 5-2 is a graphical representation of the class with its "brick
wall" built around the data to protect it. You will notice the small peep
holes we have opened up to allow the user to gain access to the functions
<B>get()</B> and <B>get_value()</B>. The peep holes were opened by declaring
the functions in the public section of the class.

<P><B>WHAT IS A PUBLIC SECTION?</B>

<P>A new keyword, <B>public</B>, is introduced in line 7 which states that
anything following this keyword can be accessed from outside of this class.
Because the two functions are declared following the keyword <B>public</B>,
they are both public and available for use by any calling program that
is within the scope of this object. This essentially opens two small peepholes
in the solid wall of protection that we built around the class. You should
keep in mind that the private variable is not available to the calling
program. Thus, we can only use the variable by calling one of the two functions
defined within the public part of the class. These are called member functions
because they are members of the class.

<P>Since we have declared two functions, we need to define them by saying
what each function will actually do. This is done in lines 12 through 20
where they are each defined in the normal way, except that the class name
is prepended onto the function name and separated from it by a double colon.
These two function definitions are called the implementation of the functions.
The class name is required because we can use the same function name in
other classes and the compiler must know with which class to associate
each function implementation.

<P><IMG SRC="CPP0503.GIF" HSPACE=20 VSPACE=20 BORDER=0 HEIGHT=346 WIDTH=351>
<BR>One of the key points to be made here is that the private data contained
within the class is available within the implementation of the member functions
of the class for modification or reading in the normal manner. You can
do anything with the private data within the function implementations which
are a part of that class, but the private data of other classes is hidden
and not available within the member functions of this class. This is the
reason we must prepend the class name to the function names of this class
when defining them. Figure 5-3 depicts the data space following execution
of line 30.

<P>It would be well to mention at this point that it is legal to declare
variables and functions in the private part, and additional variables and
functions in the public part also. In most practical situations, variables
are declared in only the private part and functions are declared in only
the public part of a class definition. Occasionally, variables or functions
are declared in the other part. This sometimes leads to a very practical
solution to a particular problem, but in general, the entities are used
only in the places mentioned.

<P>In C++ we have four scopes of variables, global, local, file, and class.
Global variables are available anywhere in the defining file and in other
files. Local variables are localized to a single function. File variables,
those that are defined outside of any function, are available anywhere
in a file following their definition. A variable with class scope is available
anywhere within the scope of a class, including the implementation code,
and nowhere else. The variable named <B>data_store</B> has a class scope.

<P>You must be very confused by this point since we have given a lot of
rules but few reasons for doing all of this. Stay with us and you will
soon see that there are very practical reasons for doing all of this.

<P><B>MORE NEW TERMINOLOGY</B>

<P>As with most new technologies, developers seem to delight in making
up new names for all aspects of their new pet. Object oriented programming
is no different, so we must learn new names for some of our old familiar
friends if we are going to learn how to effectively use it. To help you
learn this new programming terminology, we will list a few of them here
and begin using them in the text to get you used to seeing and using them.
You will not understand them all yet, but we need to introduce them early.
<UL>
<LI>
A <B>class </B>is a grouping of data and methods (functions). A class is
very much like a structure type as used in ANSI-C, it is only a pattern
to be used to create a variable which can be manipulated in a program.</LI>

<LI>
An <B>object </B>is an instance of a class, which is similar to a variable
defined as an instance of a type. An object is what you actually use in
a program since it contains values and can be changed.</LI>

<LI>
A <B>method </B>is a function contained within the class. You will find
the functions used within a class often referred to as methods in programming
literature.</LI>

<LI>
A <B>message </B>is the same thing as a function call. In object oriented
programming, we send messages instead of calling functions. For the time
being, you can think of them as identical. Later in this tutorial we will
see that they are in fact slightly different.</LI>
</UL>
With all the new terminology, we will continue our study of the program
named CLAS.CPP and show you how to use the class. We can now say that we
have a class composed of one variable and two methods. The methods operate
on the variable contained in the class when they receive messages to do
so. In this tutorial we will use the terms object and variable interchangeably
because both names are very descriptive of what the object really is.

<P>This is a small point but it could be easily overlooked. Lines 8 and
9 of this program are actually the prototypes for the two methods, and
is our first example of the use of a prototype within a class. This is
the reason we spent extra time studying prototypes in the last chapter.
You will notice line 8 which says that the method named <B>set() </B>requires
one parameter of type <B>int </B>and returns nothing, hence the return
type is <B>void</B>. The method named <B>get_value()</B> however, according
to line 9, has no input parameters but returns an <B>int </B>type value
to the caller.

<P><B>SENDING A MESSAGE</B>

<P>Following all of the definitions in lines 1 through 20, we finally come
to the program where we actually use the class. In line 24 we define three
objects of the class <B>one_datum</B> and name the objects <B>dog1</B>,
<B>dog2</B>, and <B>dog3</B>. You will notice that the keyword <B>class
</B>is not included in this line because it is not needed. Each object
contains a single data point which we can set through use of the method
<B>set()</B> or read through use of the method <B>get_value()</B>, but
we cannot directly set or read the value of the data point because it is
hidden within the "block wall" around the class. In line 27, we send a
message to the object named <B>dog1 </B>instructing it to set its internal
value to 12, and even though this looks like a function call, it is properly
called sending a message to a method. Remember that the object named <B>dog1
</B>has a method associated with it called <B>set()</B> that sets its internal
value to the actual parameter included within the message. You will notice
that the form is very much like the means of accessing the elements of
a structure. You mention the name of the object with a dot connecting it
to the name of the method. In a similar manner, we send a message to each
of the other two objects, <B>dog2 </B>and <B>dog3, </B>to set their values
to those indicated.

<P>Lines 32 and 33 have been commented out because the operations are illegal.
The variable named <B>data_store</B> is <B>private</B> and therefore not
available to the code outside of the object itself. It should be obvious,
but it will be pointed out that the data contained within the object named
<B>dog1 </B>is not available within the methods of <B>dog2 </B>or <B>dog3
</B>because they are different objects. These rules are all devised to
help you develop better code more quickly and you will soon see how they
help.

<P>The other method defined for each object is used in lines 35 through
37 to illustrate how it can be used. In each case, another message is sent
to each object and the returned result is output to the monitor via the
stream library.

<P><B>USING A NORMAL VARIABLE</B>

<P>There is another variable named <B>piggy </B>declared and used throughout
this example program that illustrates that a normal variable can be intermixed
with the objects and used in the normal manner. The use of this variable
should pose no problem to you, so after you understand the program, be
sure to compile and execute it. It would be a good exercise for you to
remove the comments from lines 32 and 33 to see what kind of error message
your compiler issues.

<P>This program illustrates information hiding but it will not be clear
to you that it really does anything worthwhile until we study the next
two programs. Be sure to compile and execute this program, then remove
the comments from lines 32 and 33 as suggested, to see the error messages
issued.

<P><B>A PROGRAM WITH PROBLEMS</B>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -