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

📄 ch04.htm

📁 C++ From Scratch: An Object-Oriented Approach is designed to walk novice programmers through the ana
💻 HTM
📖 第 1 页 / 共 4 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD><SCRIPT LANGUAGE="JavaScript"><!--function popUp(pPage) { var fullURL = document.location; var textURL = fullURL.toString(); var URLlen = textURL.length; var lenMinusPage = textURL.lastIndexOf("/"); lenMinusPage += 1; var fullPath = textURL.substring(0,lenMinusPage); popUpWin = window.open('','popWin','resizable=yes,scrollbars=no,width=525,height=394'); figDoc= popUpWin.document; zhtm= '<HTML><HEAD><TITLE>' + pPage + '</TITLE>'; zhtm += '</head>'; zhtm += '<BODY bgcolor="#FFFFFF">'; zhtm += '<IMG SRC="' + fullPath + pPage + '">'; zhtm += '<P><B>' + pPage + '</B>'; zhtm += '</BODY></HTML>'; window.popUpWin.document.write(zhtm); window.popUpWin.document.close(); // Johnny Jackson 4/28/98 }//-->                                                                </SCRIPT>	<META NAME="Author" Content="Steph Mineart">	<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1">	<TITLE>C++ From Scratch -- Ch 4 -- Creating Classes</TITLE><link rel="stylesheet" href="/includes/stylesheets/ebooks.css"></head><BODY TEXT="#000000" BGCOLOR="#FFFFFF"><CENTER><H1><IMG SRC="../button/que.gif" WIDTH="171" HEIGHT="66" ALIGN="BOTTOM" BORDER="0"><BR>C++ From Scratch</H1></CENTER><CENTER>  <P><A HREF="../index.htm"><IMG SRC="../button/contents.gif" WIDTH="128"HEIGHT="28" ALIGN="BOTTOM" ALT="Contents" BORDER="0"></A>   <HR>  <h1>4 <a name="_Toc444149693"></a></h1>  <h1> Creating Classes</h1></CENTER><ul>  <li><a href="#Heading2">Why Classes?</a>   <li><a href="#Heading3">Creating New Types: Class</a>   <li><a href="#Heading4">Interface Versus Implementation</a>     <ul>      <li><a href="#Heading5">Clients</a>     </ul>  <li><a href="#Heading6">Looking at the Code</a>   <li><a href="#Heading7"> Declaring the Class</a>     <ul>      <li><a href="#Heading8">Classes and Objects</a>       <li><a href="#Heading9">Member Variables</a>       <li><a href="#Heading10">Member Methods or Functions</a>       <li><a href="#Heading11">The Size of Objects</a>     </ul>  <li><a href="#Heading12">Files</a>   <li><a href="#Heading13">Constructors</a>     <ul>      <li><a href="#Heading14">Destructors</a>     </ul>  <li><a href="#Heading15">Implementing the Methods</a>   <li><a href="#Heading16">Including the Header</a>   <li><a href="#Heading17">Implementing the Constructor</a>   <li><a href="#Heading18">Initialization</a>     <ul>      <li><a href="#Heading19">Using the Debugger</a>     </ul>  <li><a href="#Heading20">Examining the Constructor</a>   <li><a href="#Heading21">The Other Methods</a>   <li><a href="#Heading22">Storing the Pattern</a>   <li><a href="#Heading23">What Is an Array?</a>     <ul>      <li><a href="#Heading24">Initializing Arrays</a>       <li><a href="#Heading25">Array Elements</a>       <li><a href="#Heading26">Writing Past the End of an Array</a>     </ul>  <li><a href="#Heading27">Generating the Solution</a>   <li><a href="#Heading28">Examining the Defined Values File</a> </ul><hr size=4><h2><a name="_Toc450552529"></a><a name="_Toc450554038"></a><a name="_Toc440589230"></a><a name="_Toc444149692"></a> </h2><p>In Chapter 3, "Program Flow," you began to put logic into <tt>main()</tt> to   gather the user's preference. In this chapter you'll look at creating classes   to do this work. <a name="_Toc444149694"></a><a name="_Toc450554040"></a></p><h2> <a name="Heading2">Why Classes?</a></h2><p>Although it is possible--and perhaps tempting--to just flesh out <tt>main()</tt>   with the additional functionality you want to add to this program, it is a very   bad idea.</p><p>The point of object-oriented programming is to create objects and assign them   responsibility for specific aspects of the game. This fosters encapsulation,   and with it maintainability and extensibility. </p><p><i>Maintainability</i> means that the programs can be maintained at less expense.   <i>Extensibility</i> means that you can add features without breaking the existing   code. </p><p>As we design and implement classes, I'll discuss <i>design heuristics</i>:   guidelines for designing excellent software. </p><blockquote>  <hr>  <p><strong> </strong> <b>design heuristics</b>--Guidelines for quality in design</p>  <hr></blockquote><p>The very first--and perhaps most important--object-oriented design heuristic   is that each class needs to have a single area of responsibility, and each object   needs to collaborate with other objects to accomplish more complicated tasks.</p><p>As a rule, C++ programmers tend to keep <tt>main()</tt> very simple. Its job   is only to create the first object and set off the chain of events that lead   to these objects accomplishing their assigned tasks.</p><p>You'll begin by creating a <tt>Game</tt> class that is responsible for keeping   track of the user's preferences and getting the game underway. <a name="_Toc444149695"></a><a name="_Toc450554041"></a></p><h2> <a name="Heading3">Creating New Types: Class</a></h2><p>Although the built-in types are fine for storing values, they are limited in   the complexity of the information they can manage. </p><p>Built-in types can be combined, however, into user-defined types that can be   far more complex. </p><p>For example, suppose you want to store the number of letters from which you'll   allow the player to choose and the number of positions (for example, choosing   among three numbers in two positions, without duplicates, makes the following   codes possible: <tt>ab</tt>, <tt>ba</tt>, <tt>ac</tt>, <tt>ca</tt>, <tt>bc</tt>,   and <tt>cb</tt>). You can store these two values in variables, or you can store   both of them along with the decision as to whether to allow duplicates--all   within a <tt>Game</tt> class.</p><p>A class not only has values--it also has capabilities. Just as you know that   an <tt>int</tt> can be added, subtracted, multiplied, and divided, a <tt>Game</tt>   can be set up, played, restarted, quit, and saved. <a name="_Toc441891045"></a><a name="_Toc444149696"></a><a name="_Toc450554042"></a></p><h2> <a name="Heading4">Interface Versus Implementation</a></h2><p>We draw a sharp distinction between the declaration of a class and its implementation.   The declaration of a class tells the compiler about the attributes of the class   and what its capabilities are. We often refer to this declaration as the class's   <i>interface</i>. </p><p>Every method that is declared in the interface must be implemented: You must   write the code that shows how it works. </p><blockquote>  <hr>  <p><strong> </strong> <b>interface</b>--The declaration of the methods of a     class</p>  <p> <b>implementation</b>--The code showing how the class methods work <a name="_Toc441891046"></a><a name="_Toc444149697"></a></p>  <hr></blockquote><h3> <a name="Heading5">Clients</a></h3><p>Classes provide services to clients of the class. The client of your class   is any programmer (even you!) who creates instances of your class in his code. </p><blockquote>  <hr>  <p><strong>NOTE: </strong> It is regrettable that the generic pronoun in Standard     English is masculine, and this is especially exacerbated by the fact that     the programming profession is disproportionately male. Please understand that     the masculine pronoun is intended to be generic.</p>  <p> Programmers use the term <i>client</i> in many ways. For example, if class     A calls a method in Class B, we say that A is a client of B. If I write class     A and I call code you wrote in class B, I am a client of your code. If my     computer calls code running on your computer, my computer is a client of your     (server) computer. And so on.</p>  <p> All these share the same essential characteristic: The client receives a     service from the server.</p>  <hr></blockquote><p>The client of your class needs to know what your class does, but not how it   works. If you create an <tt>employee</tt> class, your client needs to know that   the employee can tell him his hire date, but your client does not need to know   how your <tt>employee</tt> class keeps track of that date. You can store it   in memory, on disk, or in a central database, but that is not important to your   client. He cares about the interface (<i>can supply date</i>), not the implementation   (<i>retrieve date from file</i>). Thus, the client treats your code as a <i>black   box</i>.</p><blockquote>  <hr>  <p><strong> </strong> <b>client</b>--Any code that makes use of a class <a name="_Toc444149698"></a><a name="_Toc450554043"></a><a name="_Toc441891048"></a></p>  <hr></blockquote><h2> <a name="Heading6">Looking at the Code</a></h2><p>Before we discuss classes, let's take a quick look at the new code that is   declaring the <tt>Game</tt> class. Once again, there is much here that will   be new, but by reading through the code you can get a good idea of how it works--even   before we go through it in detail.</p><h4> Listing 4.1 Game.h</h4><pre><tt>0:  class Game  </tt><tt>1:  {</tt><tt>2:   public:</tt><tt>3:      Game();</tt><tt>4:      ~Game();</tt><tt>5:      void   Play();</tt><tt>6:  </tt><tt>7:      bool    duplicatesAllowed;</tt><tt>8:      int        howManyLetters;</tt><tt>9:      int        howManyPositions;</tt><tt>10:      int        round;</tt><tt>11:  };<a name="_Toc444149699"></a><a name="_Toc450554044"></a></tt></pre><h2> <a name="Heading7"> Declaring the Class</a></h2><p>A class is declared by writing the keyword <tt>class</tt>, followed by the class   name and an opening brace (as shown at line 0). The declaration is ended by   a closing brace and a semicolon. </p><blockquote>  <hr>  <p><strong>NOTE: </strong> The keyword <tt>public</tt> is needed as it is shown     in line 2. We'll cover what this word does in a later chapter. For now, please     be sure to place the keyword <tt>public</tt>, followed by a colon, at the     start of every class declaration. </p>  <hr></blockquote><h3> <a name="Heading8">Classes and Objects</a></h3><p>A <i>class</i> is a type. When you make instances of that type, they are called   <i>objects</i>. In fact, the action of creating an object is called <i>instantiation</i>.</p><blockquote>  <hr>  <p><strong> </strong> <b>class</b>--Defines a new type</p>  <p> <b>object</b>--An instance of the type defined by a class</p>  <p> <b>instantiation</b>--Creating an instance of a class: an object</p>  <hr></blockquote><p>Novice programmers often confuse classes with objects. The type of something   (the class) tells you what it is (cat), what it can do (purr, eat, jump), and   what attributes it has (weight and age). Individual objects of that type have   specific objects (nine pounds, two years old.) <a name="_Toc444149700"></a></p><h3> <a name="Heading9">Member Variables</a></h3><p>When this code was in <tt>main()</tt>, you had a number of local variables: <tt>duplicatesAllowed</tt>,   <tt>howManyLetters</tt>, <tt>howManyPositions</tt>, and <tt>round</tt>. </p><p>These variables are now moved into the class, and they become members of the   class itself starting at line 7. </p><p>Member variables represent attributes of the objects of that class type. In   other words, we are now saying that every <tt>Game</tt> object will keep track   of whether duplicates are allowed in that game, how many letters and how many   positions are to be used in the game, what the current round is, and that these   are the attributes of the class <tt>Game</tt>.</p><blockquote>  <hr>  <p><b>member variable</b>--Data that is owned by a particular object of a class,     and which represents attributes of that class. </p>  <hr></blockquote><p>Member variables are different from normal variables only in that they are   scoped to a specific class. This is actually a very powerful aspect of object-oriented   programming. The details of these values and their management are now delegated   to the <tt>Game</tt> class and can be made invisible to the clients of that   class. <a name="_Toc441891053"></a><a name="_Toc444149701"></a></p><h3> <a name="Heading10">Member Methods or Functions</a></h3><p>The <tt>Game</tt> class has two principal activities:</p><ul>  <li>    <p> <b>Setup</b>--Get the user's preferences and choose a secret code.</p>  </li>  <p></p>  <li>    <p> <b>Play</b>--Ask the user for guesses and score the guesses based on how       many are correct and how many are in the correct position.</p>  </li></ul><p></p><p>You provide these capabilities to a class by giving the class member methods,   which are also called <i>member functions</i>. A member method is a function   that is owned by a class--a method that is <i>scoped</i> to a particular class.</p><blockquote>  <hr>  <p><strong>NOTE: </strong> When we say that a member method is <i>scoped</i>     to a class, we mean that the identifier that is the member method is visible     only within the context of the class or an object of that class.</p>  <hr>

⌨️ 快捷键说明

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