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

📄 ch02.htm

📁 C++ From Scratch: An Object-Oriented Approach is designed to walk novice programmers through the ana
💻 HTM
📖 第 1 页 / 共 4 页
字号:
  to read. </p><h3> <a name="Heading3">using namespace std</a></h3><p>To simplify this code and to make it easier for us to focus on the issues we   care about, I'll rewrite the preceding example by adding the keywords</p><pre><tt>using namespace std;</tt></pre><p>This signals to the compiler that the code I'm writing is within the <tt>std</tt>   (standard) namespace. In effect, it tells the compiler that when it sees <tt>cout</tt>   it is to treat it like <tt>std::cout</tt>.</p><blockquote>  <hr>  <p><strong>NOTE: </strong> All the rest of the code in the book uses this trick,     which makes the code much easier to read and follow, at the cost of undermining     the protection that namespaces afford.</p>  <p> When you write your commercial applications you might want to eschew the     <tt>using</tt> <tt>namespace</tt> idiom because you might want to ensure namespace     protection.</p>  <hr></blockquote><p>Listing 2.1a is an exact replica of Listing 2.1, except that it takes advantage   of the <tt>using namespace</tt> idiom.</p><pre><tt>0:  #include &lt;iostream&gt;</tt><tt>1: using namespace std;  </tt><tt>2:  int main()</tt><tt>3:  {</tt><tt>4:       cout &lt;&lt; "Decryptix. Copyright 1999 Liberty ";</tt><tt>5:       cout &lt;&lt; "Associates, Inc. Version 0.2\n " &lt;&lt; endl;</tt><tt>6:  </tt><tt>7:       cout &lt;&lt; "There are two ways to play Decryptix: ";</tt><tt>8:       cout &lt;&lt; " either you can guess a pattern I create, ";</tt><tt>9:       cout &lt;&lt; "or I can guess your pattern.\n\n";</tt><tt>10:  </tt><tt>11:       cout &lt;&lt; "If you are guessing, I will think of a\n ";</tt><tt>12:       cout &lt;&lt; "pattern of letters (e.g., abcde).\n\n";</tt><tt>13:  </tt><tt>14:       cout &lt;&lt; "On each turn, you guess the pattern and\n";</tt><tt>15:       cout &lt;&lt; " I will tell you how many letters you \n";</tt><tt>16:       cout &lt;&lt; "got right, and how many of the correct\n";</tt><tt>17:       cout &lt;&lt; " letters were in the correct position.\n\n";</tt><tt>18:  </tt><tt>19:       cout &lt;&lt; "The goal is to decode the puzzle as quickly\n";</tt><tt>20:       cout &lt;&lt; "as possible. You control how many letters \n";</tt><tt>21:       cout &lt;&lt; "can be used and how many positions\n";</tt><tt>22:       cout &lt;&lt; " (e.g., 5 possible letters in 4 positions) \n";</tt><tt>23:       cout &lt;&lt; "as well as whether or not the pattern might\n";</tt><tt>24:       cout &lt;&lt; " contain duplicate letters (e.g., aabcd).\n\n";</tt><tt>25:  </tt><tt>26:       cout &lt;&lt; "If I'm guessing, you think of a pattern \n";</tt><tt>27:       cout &lt;&lt; "and score each of my answers.\n\n" &lt;&lt; endl;</tt><tt>28:  </tt><tt>29:       const int minLetters = 2;</tt><tt>30:       const int maxLetters = 10;</tt><tt>31:       const int minPositions = 3;</tt><tt>32:       const int maxPositions = 10;</tt><tt>33:  </tt><tt>34:       int          howManyLetters = 0, howManyPositions = 0;</tt><tt>35:       bool          duplicatesAllowed = false;</tt><tt>36:       int          round = 1;</tt><tt>37:  </tt><tt>38:       cout &lt;&lt; "How many letters? (";</tt><tt>39:       cout &lt;&lt; minLetters &lt;&lt; "-" &lt;&lt; maxLetters &lt;&lt; "): ";</tt><tt>40:       cin &gt;&gt; howManyLetters;</tt><tt>41:  </tt><tt>42:       cout &lt;&lt; "How many positions? (";</tt><tt>43:       cout &lt;&lt; minPositions &lt;&lt; "-" &lt;&lt; maxPositions &lt;&lt; "): ";</tt><tt>44:       cin &gt;&gt; howManyPositions;</tt><tt>45:  </tt><tt>46:       char     choice;</tt><tt>47:       cout &lt;&lt; "Allow duplicates (y/n)? ";</tt><tt>48:       cin &gt;&gt; choice;</tt><tt>49:  </tt><tt>50:       return 0;</tt><tt>51:  }</tt></pre><p><b>Code Spelunking</b></p><p>One of the most powerful ways to learn C++ is to use your debugger. I highly   recommend that immediately after entering this code into your project (or downloading   it from my site), you compile, link, and run it. You'll need to check your documentation   for how to do this, but most modern IDEs offer a menu choice to "Build the entire   project." </p><p>If you are using Visual C++, you can simply point your cursor at the buttons   on the toolbar until you find the ones that compile and link or that build the   entire project.</p><p>After it is working, set this book aside and pick up the documentation for   your debugger, which you'll find with the documentation for your compiler. Set   a break point on the first line of code in <tt>main()</tt> (see line 5 in Listing   2.1). In Visual C++ you just put your cursor on that line and press <b>F9</b>,   or press the break point toolbar button. Once the break point is set, run to   the break point (in Visual C++, press <b>F5</b>). Step over each line of code   and try to guess what is going on. Again, you'll need to check your documentation   for how to step over each line of code (in Visual C++ it is <b>F10</b>). </p><p>The debugger is one of the last things most primers introduce; I feel that   it needs to be one of the very <i>first</i> things you learn. If you get stuck,   see the exploration of debugging at the end of this chapter.</p><p>Every C++ program has a <tt>main()</tt> function (Listing 2.1, line 2). The   general purpose of a function is to run a little code and then return to whomever   called you. </p><blockquote>  <hr>  <p> All functions begin and end with parentheses, as you can see on lines 3     and 51. A <i>function</i> consists of a series of statements, which are all     the lines that are shown between the parentheses.</p>  <hr></blockquote><p>This is the essence of a structured program. Program flow continues in the   order in which the code appears in the file until a function is called. The   flow then branches off to the function and follows line by line until another   function is called or until the function returns (see Figure 2.2). </p><p>In a sense, a function is a subprogram. In some languages, it is called a <i>subroutine</i>   or a <i>procedure</i>. The job of a function is to accomplish some work and   then return control to whatever invoked the function.</p><p><b>Figure 2.2 </b><i>When a program calls a fuction, execution switches to   the function and then resumes at the line after the function call.</i></p><p>When <tt>main()</tt> executes, we execute <tt>Statement1</tt>. We then branch   to line 1 of <tt>Func1().</tt> <tt>Func1</tt>'s three lines execute, and then   processing returns to <tt>main()</tt>, where we execute <tt>Statement2</tt>.   <tt>Func2</tt> is then called, which in turn calls <tt>Func3().</tt> When <tt>Func3</tt>   completes it returns to <tt>Func2(),</tt> which continues to run until its own   <tt>return</tt> statement, at which time we return to <tt>main()</tt> and execute   <tt>Statement3</tt>. We then call <tt>Func4()</tt>, which executes its own code   and then returns to <tt>main()</tt>, where we execute <tt>Statement4</tt>.  </p><h3> <a name="Heading4">Returning a Value</a></h3><p>When a function returns to whoever called it, it can return a value. You'll   see later what the calling function can do with that value. </p><p>Every function must declare what kind of value it returns: For example, does   it return an integer or a character? If a function does not return a value,   it declares itself to return <tt>void</tt>, which means that it returns nothing.    </p><h3> <a name="Heading5">main() Is More Equal than Others</a></h3><p><tt>main()</tt> is a special function in C++. All C++ programs begin with <tt>main()</tt>;   when <tt>main</tt> ends, the program ends. In a sense, the operating system   (Windows, DOS, and so on) calls <tt>main()</tt>.</p><p><tt>main()</tt> always returns an <tt>int</tt> (integer). I'll discuss the   various types of values later in the book; for now it is sufficient to know   that you must always declare <tt>main</tt> to return an integer. </p><blockquote>  <hr>  <p><strong>NOTE: </strong> On some older compilers, you can have <tt>main()</tt>     return <tt>void</tt>, but that is not legal under the new ISO standard. It     is a good idea to get into the habit of having <tt>main()</tt> return an <tt>int</tt>     every time.</p>  <hr></blockquote><p>You'll notice that <tt>main()</tt> does return an integer (in this case, <tt>0</tt>)   on line 50. When programs are run from batch files or scripts, you can examine   these values. For the programs in this book (and probably for most of the programs   you will write), this value is discarded. By convention, you'll return <tt>0</tt>   to indicate that the program ran without incident.  </p><h3> <a name="Heading6">Using cout to Print to the Screen</a></h3><p>Most of the statements in this very first program are designed to write to   the screen. Use the standard output object <tt>cout</tt>. You send a string   of characters to <tt>cout</tt> by enclosing them in quotation marks and by using   the output redirection operator (<tt>&lt;&lt;</tt>), which you create by holding   the Shift key and pressing the comma key twice.</p><p>This actually takes advantage of a very advanced feature in C++ called <i>operator   overloading</i>, which is discussed in detail in Chapter 6, "Using Linked Lists."   Fortunately, for now you can use this feature without fully understanding it.   The net effect is that the words</p><pre><tt>Decryptix. Copyright 1999 Liberty</tt></pre><p>are sent to the screen. </p><blockquote>  <hr>  <p> <b>Operator Overloading</b>--The capability of user-created types to use     the operators that built-in types use, such as <tt>+</tt>, <tt>=</tt>, and     <tt>==</tt>. I explain how to do this in Chapter 6.  </p>  <hr></blockquote><h4>Special Printing Characters</h4><p>Line 5 prints the words</p><pre><tt>Associates, Inc. Version 0.2</tt></pre><p>to the screen. Notice that before the closing quotes, line 5 includes <tt>\n</tt>.   These are two special marks within quoted strings. The slash is called an <i>escape   character</i>, and when it is found in a quoted string it means "what follows   is a special instruction to the compiler." The letter <i>n</i>, when it follows   the escape character, stands for "new line." Thus, the effect is to print, to   the output, a new line. </p><blockquote>  <hr>  <p> <b>Escape character</b>--A character that serves as a signal to the compiler     or precompiler that the letter that follows requires special treatment. For     example, the precompiler usually treats the character <i>n</i> as a letter,     but when it is preceded by the escape character (<tt>\n</tt>), it indicates     a new line.</p>  <hr></blockquote><p>Notice also that this line ends with </p><pre><tt>&lt;&lt; endl;</tt></pre><p><tt>cout</tt> can receive more than just strings. In this case, the redirection   operator is being used to send <tt>endl</tt>.</p><blockquote>  <hr>  <p><strong>NOTE: </strong> <tt>endl</tt> is pronounced <i>end-ell</i> and stands     for "end line."</p>  <hr></blockquote><p>This sends another new line to the output and flushes out the buffers. Buffers   will be explained later, when I talk about streams, but the net effect ensures   that all the text is written to the screen immediately.</p><p>Line 7 begins to print another line, which is continued on line 8 and completed   on line 9.</p><p>Together, these lines print the following output:</p><pre><tt>Decryptix. Copyright 1999 Liberty Associates, Inc. Version 0.2</tt><tt>There are two ways to play Decryptix: either you can guess a pattern I create,</tt><tt>or I can guess your pattern.</tt></pre><p>Note first that there is no new line after Liberty and before Associates. There   was no instruction to <tt>cout</tt> to print a new line, so none was printed.   Two new lines appear after <tt>0.2</tt>. The first, created by the <tt>\n</tt>   character, ends the line; the second, created by <tt>endl</tt>, skips a line.</p><p>You can achieve the effect of skipping a line by putting in two <tt>\n</tt>   characters, as shown on line 9.</p><p>Table 2.1 illustrates the other special printing characters.</p><p><b>Table 2.1Special Printing Characters </b></p><table border>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><b>Character</b></p>    </td>    <td colspan=1 align="left">       <p><b>What it means </b></p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><tt>\n</tt></p>    </td>    <td colspan=1 align="left">       <p>new line </p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><tt>\t</tt></p>    </td>    <td colspan=1 align="left">       <p>tab</p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><tt>\b</tt></p>    </td>    <td colspan=1 align="left">       <p>rings the bell </p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><tt>\"</tt></p>    </td>    <td colspan=1 align="left">       <p>prints a double quote </p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><tt>\'</tt></p>    </td>    <td colspan=1 align="left">       <p>prints a single quote </p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><tt>\?</tt></p>    </td>    <td colspan=1 align="left">       <p>prints a question mark </p>    </td>  </tr>  <tr valign="TOP" align="left">     <td colspan=1 align="left">       <p><tt>\\</tt></p>    </td>    <td colspan=1 align="left">       <p>prints a backslash </p>    </td>  </tr>    </table><h3> <a name="Heading7"> Variables</a></h3><p>A <i>variable</i> is a place to store a value during the progress of your program. </p><blockquote>  <hr>  <p> <b>Variable</b>--A place to store a value</p>  <hr></blockquote><p>In this case, at line 36, you want to keep track of what round of play you   are up to. Store this information in a variable named <tt>round</tt>:</p><pre><tt>int round = 1;</tt></pre><p>One way to think of your computer's memory is as a series of cubbyholes. Each   cubbyhole is one byte, and every byte is numbered sequentially: The number is   the address of that memory. Each variable reserves one or more bytes in which   you can store a value.</p><p>Your variable's name (<tt>round</tt>) is a label on one of these cubbyholes,   which enables you to find it easily without knowing its actual memory address. </p><p>Think of it like this: When you jump in a cab in Washington, D.C., you can   ask for 1600 Pennsylvania Avenue, or you can ask for The White House. The identifier   "the White House" is the name of that address.</p><p>Figure 2.3 is a schematic representation of this idea. As you can see from   the figure, <tt>round</tt> starts at memory address 103. Depending on the size   of <tt>round</tt>, it can take up one or more memory addresses.</p><p></p><p><b>Figure 2.3 </b><i>A schematic representation of memory.</i></p><blockquote>  <hr>  <p> <i>RAM</i> is <i>random access memory</i>. When you run your program, it     is loaded into RAM from the disk file. All variables are also created in RAM.     When programmers talk about memory, they are usually referring to RAM.  </p>  <hr></blockquote><h4>Setting Aside Memory</h4><p>When you define a variable in C++, you must tell the compiler what kind of   variable you are declaring: an <tt>int</tt>, <tt>char</tt>, and so forth. The 

⌨️ 快捷键说明

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