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

📄 chap05.txt

📁 含有文章和源码
💻 TXT
📖 第 1 页 / 共 3 页
字号:
executed.



THE CLASS IMPLEMENTATION FILE
_________________________________________________________________

Examine the file named BOX.CPP for the            ===============
implementation of the methods declared in the         BOX.CPP
class header file.  Notice that the class header  ===============
file is included into this file in line 2 which
contains all of the prototypes for its methods.
The code from lines 15 through 34 of BOXES1.CPP is contained in
this file which is the implementation of the methods declared in
the class named box.


                                                        Page 5-11

                                        Chapter 5 - Encapsulation

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 method of
object oriented programming was ever considered.

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.

You should compile this implementation file now and we will use the
result with the next example program.



USING THE BOX OBJECT
_________________________________________________________________

Examine the file named BOXES2.CPP and you will   ================
find that the class we defined previously is        BOXES2.CPP
used within this file.  In fact, these last      ================
three programs taken together are identical to
the program named BOXES1.CPP studied earlier.

The BOX.H file is included here, in line 3, since the definition
of the box 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.

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 in 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

                                                        Page 5-12

                                        Chapter 5 - Encapsulation

it to work with as parameters since it doesn't contain its own
data.

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
box.  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.  Even if it seems to be a lot of
trouble to learn how to link several files together, it will be
worth your time to do so now because we will be linking several
more multifile C++ programs in the remainder of this tutorial.

If you are using Turbo C++, this is your first opportunity to use
a project file.  If you are using Zortech C++ or one of the other
implementations, you can use 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.


INFORMATION HIDING
_________________________________________________________________

The last three example programs 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.

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.



                                                        Page 5-13

                                        Chapter 5 - Encapsulation

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 some
amount of forethought to effectively use classes.


ABSTRACT DATA TYPES
_________________________________________________________________

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 of its class outside
the scope.

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.

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.


FRIEND FUNCTIONS
_________________________________________________________________

A function outside of a class can be defined to be a friend
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

                                                        Page 5-14

                                        Chapter 5 - Encapsulation

entire classes can be given friend status if needed in a program.
Neither a constructor nor a destructor can be a friend function.


THE struct IN C++
_________________________________________________________________

The struct 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 all methods and data are automatically defaulted to be public
in 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.



A VERY PRACTICAL CLASS
_________________________________________________________________

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 date class is given below for your instruction.  The
date 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.

Examine the file named DATE.H which is the         ==============
header file for the date class.  This file is so       DATE.H
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.  The first thing that is new to
you is the reserved word protected which is used in line 12.  We
will define this word in a couple of chapters.  Until then, pretend
that it means the same thing as private and you will be close
enough for this present example.  The code in lines 8 and 9 along
with line 55 will be explained shortly.  For the present time,
simply pretend those lines of code are not there.  Also the keyword
static as used in lines 16 and 17 will be explained later.

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.

The file named DATE.CPP is the implementation      ==============
for the date class and once again, there is           DATE.CPP
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

                                                        Page 5-15

                                        Chapter 5 - Encapsulation

this code until you understand it completely before going on to the
next example which will use the date class in a main program.

The very simple program named USEDATE.CPP is a    ===============
main program that uses the date class to list       USEDATE.CPP
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.

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.

We will continue our discussion of encapsulation in the next
chapter.


PROGRAMMING EXERCISES
_________________________________________________________________

1.   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.

2.   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.

3.   Add an output statement to the rectangle 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.

4.   Write a more comprehensive program to use the date class
     presented at the end of this chapter.

5.   Write a name class which is somewhat similar to the date class
     which can store any name in three parts and return the full
     name in any of several different formats such as the
     following;

           John Paul Doe
           J. P. Doe
           Doe, John Paul
             and any other formats you desire.

     If this is carefully planned, it could be useful to you
     someday.

                                                        Page 5-16

⌨️ 快捷键说明

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