📄 chap05.htm
字号:
except of course for the inline method named <B>get_area()</B>. This gives
the complete definition of how to use the class with no implementation
details. You would be advised to keep a hardcopy of this file available
as we study the next two files. You will notice that it contains lines
4 through 13 of the previous example program named BOXES1.CPP. This is
called the class header file and cannot be compiled or executed.
<P><B>THE CLASS IMPLEMENTATION FILE</B>
<P>Example program ------> <B><A HREF="BOX.CPP">BOX.CPP</A></B>
<P>Examine the file named BOX.CPP for the implementation of the methods
declared in the class header file. Notice that the class header file is
included into this file in line 2 which contains the prototypes for its
methods and the definitions of the variables to be manipulated. The code
from lines 16 through 35 of BOXES1.CPP is contained in this file which
is the implementation of the methods declared in the class named <B>box</B>.
<P>This file can be compiled but it cannot be executed because there is
no main entry point which is required for all ANSI-C or C++ programs. When
it is compiled, the object code will be stored in the current directory
and available for use by other programs. It should be noted here that the
result of compilation is usually referred to as an object file because
it contains object code. This use of the word object has nothing to do
with the word object as used in object oriented programming. It is simply
a matter of overloading the use of the word. The practice of referring
to the compiled result as an object file began long before the technique
of object oriented programming was ever considered.
<P>The separation of the definition and the implementation is a major step
forward in software engineering. The definition file is all the user needs
in order to use this class effectively in a program. He needs no knowledge
of the actual implementation of the methods. If he had the implementation
available, he may study the code and find a trick he could use to make
the overall program slightly more efficient, but this would lead to nonportable
software and possible bugs later if the implementor changed the implementation
without changing the interface. The purpose of object oriented programming
is to hide the implementation in such a way that the implementation can
not affect anything outside of its own small and well defined boundary
or interface.
<P>You should compile this implementation file now and we will use the
result with the next example program.
<P><B>USING THE BOX OBJECT</B>
<P>Example program ------> <B><A HREF="BOXES2.CPP">BOXES2.CPP</A></B>
<P>Examine the file named BOXES2.CPP and you will find that the class we
defined previously is used within this file. In fact, these last three
programs taken together are identical to the program named BOXES1.CPP studied
earlier.
<P>The BOX.H file is included here, in line 3, since the definition of
the <B>box </B>class is needed to declare three objects and use their methods.
You should have no trouble seeing that this is a repeat of the previous
program and will execute in exactly the same way. There is a big difference
in BOXES1.CPP and BOXES2.CPP as we will see shortly.
<P>A very important distinction must be made at this point. We are not
merely calling functions and changing the terminology a little to say we
are sending messages. There is an inherent difference in the two operations.
Since the data for each object is tightly bound up within the object, there
is no way to get to the data except through the methods and we send a message
to the object telling it to perform some operation based on its internally
stored data. However, whenever we call a function, we take along the data
for it to work with as parameters since it doesn't contain its own data.
Admittedly, the difference is slight, but you will see the new terminology
used in the literature, and you need to realize that there is a slight
difference.
<P>Be sure to compile and execute this program, but when you come to the
link step, you will be required to link this program along with the result
of the compilation when you compiled the class named <B>box</B>. The file
is probably named BOX.OBJ that must be linked with this file. You may need
to consult the documentation for your C++ compiler to learn how to do this.
<P>Depending on your compiler, this is your first opportunity to use either
a project file, or the "make" facility included with your compiler. Regardless
of which C++ compiler you are using, it would pay you to stop and learn
how to use the multifile technique provided with your compiler because
you will need to use it several times before the end of this tutorial.
The nature of C++ tends to drive the programmer to use many files for a
given programming project and you should develop the habit early.
<P><B>INFORMATION HIDING</B>
<P>The three example programs we have just studied illustrate a method
of information hiding that can have a significant impact on the quality
of software developed for a large project. Since the only information the
user of the class really needs is the class header, that is all he needs
to be given. The details of implementation can be kept hidden from him
to prevent him from studying the details and possibly using a quirk of
programming to write some rather obtuse code. Since he doesn't know exactly
what the implementor did, he must follow only the definition given in the
header file. This can have a significant impact on a large project. As
mentioned earlier, accidental corruption of data is prevented also.
<P>Another reason for hiding the implementation is economic. The company
that supplied you with your C++ compiler gave you many library functions
but did not supply the source code to the library functions, only the interface
to each function. You know how to use the file access functions but you
do not have the details of implementation, nor do you need them. Likewise
a class library industry can develop which supplies users with libraries
of high quality, completely developed and tested classes, for a licensing
fee of course. Since the user only needs the interface defined, he can
be supplied with the interface and the object (compiled) code for the class
and can use it in any way he desires. The suppliers source code is protected
from accidental or intentional compromise and he can maintain complete
control over it.
<P>It is very important that you understand the principles covered in this
chapter before proceeding on to the next chapter. If you feel you are a
little weak in any of the areas covered here, you should go over them again
before proceeding on. A point that should be made here that may be obvious
to you, is that it requires a considerable amount of forethought to effectively
use classes.
<P><B>ABSTRACT DATA TYPES</B>
<P>We mentioned the abstract data type at the beginning of this chapter
and again briefly midway through, and it is time to describe it a little
more completely. An abstract data type is a group of data, each of which
can store a range of values, and a set of methods or functions that can
operate on that data. Since the data are protected from any outside influence,
it is protected and said to be encapsulated. Also, since the data is somehow
related, it is a very coherent group of data that may be highly interactive
with each other, but with little interaction outside the scope of its class.
<P>The methods, on the other hand, are coupled to the outside world through
the interface, but there are a limited number of contacts with the outside
world and therefore a weak coupling with the outside. The object is therefore
said to be loosely coupled to the outside world. Because of the tight coherency
and the loose coupling, ease of maintenance of the software is greatly
enhanced. The ease of maintenance may be the greatest benefit of object
oriented programming.
<P>It may bother you that even though the programmer may not use the private
variables directly outside of the class, they are in plain sight and he
can see what they are and can probably make a good guess at exactly how
the class is implemented. The variables could have been hidden completely
out of sight in another file, but because the designers of C++ wished to
make the execution of the completed application as efficient as possible,
the variables were left in the class definition where they can be seen
but not used.
<P><B>FRIEND FUNCTIONS</B>
<P>A function outside of a class can be defined to be a <B>friend </B>function
by the class which gives the friend free access to the private members
of the class. This in effect, opens a small hole in the protective shield
of the class, so it should be used very carefully and sparingly. There
are cases where it helps to make a program much more understandable and
allows controlled access to the data. Friend functions will be illustrated
in some of the example programs later in this tutorial. It is mentioned
here for completeness of this section. A single isolated function can be
declared as a friend, as well as members of other classes, and even entire
classes can be given friend status if needed in a program. Neither a constructor
nor a destructor can be a friend function.
<P><B>THE struct IN C++</B>
<P>The <B>struct </B>is still useable in C++ and operates just like it
does in ANSI-C with one addition. You can include methods in a structure
that operate on data in the same manner as in a class, but methods and
data are automatically defaulted to be public at the beginning of a structure.
Of course you can make any of the data or methods private by defining a
private section within the structure. The structure should be used only
for constructs that are truly structures. If you are building even the
simplest objects, you are advised to use classes to define them.
<P><B>A VERY PRACTICAL CLASS</B>
<P>The examples of encapsulation used in this chapter have all been extremely
simple in order to illustrate the mechanics of encapsulation. Since it
would be expedient to study a larger example, the <B>date </B>class is
given for your instruction. The <B>date </B>class is a complete nontrivial
class which can be used in any program to get the current date and print
it as an ASCII string in any of four predefined formats. It can also be
used to store any desired date and format it for display.
<P>Example program ------> <B><A HREF="DATE.H">DATE.H</A></B>
<P>Examine the file named DATE.H which is the header file for the <B>date
</B>class. This file is so well commented that we don't have much else
to say about it. If you understand the principles covered in this chapter
you should have no problem understanding this class. One thing that is
new to you is the reserved word <B>protected </B>which is used in line
13. We will define this word in a couple of chapters. Until then, pretend
that it means the same thing as <B>private </B>and you will be close enough
for this present example. The code in lines 8 and 9 along with line 58
will be explained shortly. For the present time, simply pretend those lines
of code are not there. Also the keyword <B>static </B>as used in lines
18 and 19 will be explained later. These new constructs are added because
we plan to use this class later when we study inheritance.
<P>You should spend the time necessary to completely understand this class
header, with the exception of the new things added, before going on to
the implementation for this class.
<P>Example program ------> <B><A HREF="DATE.CPP">DATE.CPP</A></B>
<P>The file named DATE.CPP is the implementation for the <B>date </B>class
and once again, there is nothing unusual or difficult about this code.
It uses very simple logic to store and format the date in a usable manner.
You should study this code until you understand it completely before going
on to the next example which will use the <B>date </B>class in a main program.
<P>The constructor implementation in lines 14 through 25 use DOS system
calls to get the current date. Unless you are using 16 bit DOS, these calls
will not be compiled or executed properly because they are not portable.
You can modify this code so it uses calls to your system or simply assign
the member variables some default values. The purpose of this code is to
illustrate the use of encapsulation and constructors, not how to read the
real time clock and calendar on your particular computer.
<P>Example program ------> <B><A HREF="USEDATE.CPP">USEDATE.CPP</A></B>
<P>The very simple program named USEDATE.CPP is a main program that uses
the <B>date </B>class to list the current date and another date on the
monitor. Once again, you should have no problem understanding this program
so nothing more will be said about it.
<P>You should spend the time necessary to understand these three files
because they are the starting point for a practical track in the next few
chapters. This class will be used in conjunction with others to illustrate
single and multiple inheritance. Even though you do not understand all
of the details of these files, spend enough time that you are comfortable
with the structure and the major points of them.
<P>We will continue our discussion of encapsulation in the next chapter.
<P><B>PROGRAMMING EXERCISES</B>
<OL>
<LI>
Add a method to CLAS.CPP which will supply the square of the stored value.
Include some code in the main program to read and display the squared values.</LI>
<LI>
Continuing with CLAS.CPP, add a constructor to initialize the stored value
to 10 and add a few lines of code to the main program to display the values
immediately following the object definition.</LI>
<LI>
Add an output statement to the <B>rectangle </B>constructor of the program
named CONSPOLE.CPP and another to the destructor to prove to yourself that
they really are called by the system when we said they are.</LI>
<LI>
Write a more comprehensive program to use the <B>date </B>class presented
at the end of this chapter.</LI>
<LI>
Write a <B>name </B>class which is somewhat similar to the <B>date </B>class
which can store any name in three parts and return the full name in any
of several different formats such as the following;</LI>
</OL>
<PRE> John Paul Doe
J. P. Doe
Doe, John Paul
and any other formats you desire.</PRE>
<A HREF="chap06.htm">Advance to Chapter 6</A>
<P><A HREF="cpplist.htm">Return to the Table of Contents</A>
</BODY>
</HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -