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

📄 ch02.htm

📁 一本好的VC学习书,本人就是使用这本书开始学习的vc,希望能对大家有帮助
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD><!-- This document was created from RTF source by rtftohtml version 3.0.1 -->	<META NAME="GENERATOR" Content="Symantec Visual Page 1.0">	<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1">	<TITLE>Teach Yourself C++ in 21 Days</TITLE></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF"><H1 ALIGN="CENTER"><A HREF="ch01.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch01.htm"><IMG SRC="BLANPREV.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANPREV.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="tppmsgs/msgs0.htm#1" tppabs="http://www.mcp.com/sams"><IMGSRC="BLANHOME.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANHOME.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM"BORDER="0"></A><A HREF="index.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/index.htm"><IMG SRC="BLANTOC.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANTOC.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="ch03.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch03.htm"><IMG SRC="BLANNEXT.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANNEXT.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A></H1><H1></H1><UL>	<LI><A HREF="#Heading1">Day 2</A>	<UL>		<LI><A HREF="#Heading2">The Parts of a C++ Program</A>		<UL>			<LI><A HREF="#Heading3">A Simple Program</A>			<LI><A HREF="#Heading4">Listing 2.1. HELLO.CPP demonstrates the parts of a C++ program</A><A			HREF="#Heading5">.</A>			<LI><A HREF="#Heading6">A Brief Look at cout</A>			<LI><A HREF="#Heading7">Listing 2.2.</A>			<LI><A HREF="#Heading8">Using cout.</A>			<LI><A HREF="#Heading9">Comments</A>			<UL>				<LI><A HREF="#Heading10">Types of Comments</A>				<LI><A HREF="#Heading11">Using Comments</A>			</UL>			<LI><A HREF="#Heading12">Listing 2.3. HELP.CPP demonstrates comments</A><A HREF="#Heading13">.</A>			<UL>				<LI><A HREF="#Heading14">Comments at the Top of Each File</A>				<LI><A HREF="#Heading15">A Final Word of Caution About Comments</A>			</UL>			<LI><A HREF="#Heading16">Functions</A>			<LI><A HREF="#Heading17">Listing 2.4. Demonstrating a call to a function</A><A HREF="#Heading18">.</A>			<UL>				<LI><A HREF="#Heading19">Using Functions</A>			</UL>			<LI><A HREF="#Heading20">Listing 2.5. FUNC.CPP demonstrates a simple function</A><A			HREF="#Heading21">.</A>			<LI><A HREF="#Heading22">Summary</A>			<LI><A HREF="#Heading23">Q&amp;A</A>			<LI><A HREF="#Heading24">Workshop</A>			<UL>				<LI><A HREF="#Heading25">Quiz</A>				<LI><A HREF="#Heading26">Exercises</A>			</UL>		</UL>	</UL></UL><P><HR SIZE="4"><H2 ALIGN="CENTER"><BR><A NAME="Heading1"></A><FONT COLOR="#000077">Day 2</FONT></H2><H2 ALIGN="CENTER"><A NAME="Heading2"></A><FONT COLOR="#000077">The Parts of a C++Program</FONT></H2><P>C++ programs consist of objects, functions, variables, and other component parts.Most of this book is devoted to explaining these parts in depth, but to get a senseof how a program fits together you must see a complete working program. Today youlearn<UL>	<LI>The parts of a C++ program.	<P>	<LI>How the parts work together.	<P>	<LI>What a function is and what it does.</UL><H3 ALIGN="CENTER"><A NAME="Heading3"></A><FONT COLOR="#000077">A Simple Program</FONT></H3><P>Even the simple program HELLO.CPP from Day 1, &quot;Getting Started,&quot; hadmany interesting parts. This section will review this program in more detail. Listing2.1 reproduces the original version of HELLO.CPP for your convenience.</P><P><A NAME="Heading4"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 2.1. HELLO.CPPdemonstrates the parts of a C++ program.</B></FONT><FONT SIZE="2" COLOR="#000077"></FONT><PRE><FONT COLOR="#0066FF">1: #include &lt;iostream.h&gt;2:3:  int main()4: {5:    cout &lt;&lt; &quot;Hello World!\n&quot;;6:      return 0;7: }Hello World!</FONT></PRE><P>On line 1, the file iostream.h is included in the file. The first character isthe # symbol, which is a signal to the preprocessor. Each time you start your compiler,the preprocessor is run. The preprocessor reads through your source code, lookingfor lines that begin with the pound symbol (#), and acts on those lines before thecompiler runs.</P><P>include is a preprocessor instruction that says, &quot;What follows is a filename.Find that file and read it in right here.&quot; The angle brackets around the filenametell the preprocessor to look in all the usual places for this file. If your compileris set up correctly, the angle brackets will cause the preprocessor to look for thefile iostream.h in the directory that holds all the H files for your compiler. Thefile iostream.h (Input-Output-Stream) is used by cout, which assists with writingto the screen. The effect of line 1 is to include the file iostream.h into this programas if you had typed it in yourself.</P><P>New Term: The preprocessor runs before your compiler each time the compiler isinvoked. The preprocessor translates any line that begins with a pound symbol (#)into a special command, getting your code file ready for the compiler.</P><P>Line 3 begins the actual program with a function named main(). Every C++ programhas a main() function. In general, a function is a block of code that performs oneor more actions. Usually functions are invoked or called by other functions, butmain() is special. When your program starts, main() is called automatically.</P><P>main(), like all functions, must state what kind of value it will return. Thereturn value type for main() in HELLO.CPP is void, which means that this functionwill not return any value at all. Returning values from functions is discussed indetail on Day 4, &quot;Expressions and Statements.&quot;</P><P>All functions begin with an opening brace ({) and end with a closing brace (}).The braces for the main() function are on lines 4 and 7. Everything between the openingand closing braces is considered a part of the function.</P><P>The meat and potatoes of this program is on line 5. The object cout is used toprint a message to the screen. We'll cover objects in general on Day 6, &quot;BasicClasses,&quot; and cout and its related object cin in detail on Day 17, &quot;ThePreprocessor.&quot; These two objects, cout and cin, are used in C++ to print stringsand values to the screen. A string is just a set of characters.</P><P>Here's how cout is used: type the word cout, followed by the output redirectionoperator (&lt;&lt;). Whatever follows the output redirection operator is writtento the screen. If you want a string of characters written, be sure to enclose themin double quotes (&quot;), as shown on line 5.</P><P>New Term: A text string is a series of printable characters.</P><P>The final two characters, \n, tell cout to put a new line after the words HelloWorld! This special code is explained in detail when cout is discussed on Day 17.</P><P>All ANSI-compliant programs declare main() to return an int. This value is &quot;returned&quot;to the operating system when your program completes. Some programmers signal an errorby returning the value 1. In this book, main() will always return 0.</P><P>The main() function ends on line 7 with the closing brace.<H3 ALIGN="CENTER"><A NAME="Heading6"></A><FONT COLOR="#000077">A Brief Look at cout</FONT></H3><P>On Day 16, &quot;Streams,&quot; you will see how to use cout to print data tothe screen. For now, you can use cout without fully understanding how it works. Toprint a value to the screen, write the word cout, followed by the insertion operator(&lt;&lt;), which you create by typing the less-than character (&lt;) twice. Eventhough this is two characters, C++ treats it as one.</P><P>Follow the insertion character with your data. Listing 2.2 illustrates how thisis used. Type in the example exactly as written, except substitute your own namewhere you see Jesse Liberty (unless your name is Jesse Liberty, in which case leaveit just the way it is; it's perfect-- but I'm still not splitting royalties!).</P><P><A NAME="Heading7"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 2.2.Using cout.</B></FONT><FONTCOLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1:     // Listing 2.2 using cout2:3:     #include &lt;iostream.h&gt;4:     int main()5:     {6:        cout &lt;&lt; &quot;Hello there.\n&quot;;7:        cout &lt;&lt; &quot;Here is 5: &quot; &lt;&lt; 5 &lt;&lt; &quot;\n&quot;;8:        cout &lt;&lt; &quot;The manipulator endl writes a new line to the screen.&quot; &lt;&lt;                        &#194;endl;9:        cout &lt;&lt; &quot;Here is a very big number:\t&quot; &lt;&lt; 70000 &lt;&lt; endl;10:       cout &lt;&lt; &quot;Here is the sum of 8 and 5:\t&quot; &lt;&lt; 8+5 &lt;&lt; endl;11:       cout &lt;&lt; &quot;Here's a fraction:\t\t&quot; &lt;&lt; (float) 5/8 &lt;&lt; endl;12:       cout &lt;&lt; &quot;And a very very big number:\t&quot; &lt;&lt; (double) 7000 * 7000 &lt;&lt;                       &#194;endl;13:       cout &lt;&lt; &quot;Don't forget to replace Jesse Liberty with your name...\n&quot;;14:       cout &lt;&lt; &quot;Jesse Liberty is a C++ programmer!\n&quot;;15:        return 0;16: }</FONT><FONT COLOR="#0066FF">Hello there.Here is 5: 5The manipulator endl writes a new line to the screen.Here is a very big number:      70000Here is the sum of 8 and 5:     13Here's a fraction:              0.625And a very very big number:     4.9e+07Don't forget to replace Jesse Liberty with your name...Jesse Liberty is a C++ programmer!</FONT></PRE><P>On line 3, the statement #include &lt;iostream.h&gt; causes the iostream.h fileto be added to your source code. This is required if you use cout and its relatedfunctions.</P><P>On line 6 is the simplest use of cout, printing a string or series of characters.The symbol \n is a special formatting character. It tells cout to print a newlinecharacter to the screen.</P><P>Three values are passed to cout on line 7, and each value is separated by theinsertion operator. The first value is the string &quot;Here is 5: &quot;. Note thespace after the colon. The space is part of the string. Next, the value 5 is passedto the insertion operator and the newline character (always in double quotes or singlequotes). This causes the line</P><PRE><FONT COLOR="#0066FF">Here is 5: 5</FONT></PRE><P>to be printed to the screen. Because there is no newline character after the firststring, the next value is printed immediately afterwards. This is called concatenatingthe two values.</P><P>On line 8, an informative message is printed, and then the manipulator endl isused. The purpose of endl is to write a new line to the screen. (Other uses for endlare discussed on Day 16.)</P><P>On line 9, a new formatting character, \t, is introduced. This inserts a tab characterand is used on lines 8-12 to line up the output. Line 9 shows that not only integers,but long integers as well can be printed. Line 10 demonstrates that cout will dosimple addition. The value of 8+5 is passed to cout, but 13 is printed.</P><P>On line 11, the value 5/8 is inserted into cout. The term (float) tells cout thatyou want this value evaluated as a decimal equivalent, and so a fraction is printed.On line 12 the value 7000 * 7000 is given to cout, and the term (double) is usedto tell cout that you want this to be printed using scientific notation. All of thiswill be explained on Day 3, &quot;Variables and Constants,&quot; when data typesare discussed.</P><P>On line 14, you substituted your name, and the output confirmed that you are indeeda C++ programmer. It must be true, because the computer said so!<H3 ALIGN="CENTER"><A NAME="Heading9"></A><FONT COLOR="#000077">Comments</FONT></H3><P>When you are writing a program, it is always clear and self-evident what you aretrying to do. Funny thing, though--a month later, when you return to the program,it can be quite confusing and unclear. I'm not sure how that confusion creeps intoyour program, but it always does.</P><P>To fight the onset of confusion, and to help others understand your code, you'llwant to use comments. Comments are simply text that is ignored by the compiler, butthat may inform the reader of what you are doing at any particular point in yourprogram.<H4 ALIGN="CENTER"><A NAME="Heading10"></A><FONT COLOR="#000077">Types of Comments</FONT></H4><P>C++ comments come in two flavors: the double-slash (//) comment, and the slash-star(/*) comment. The double-slash comment, which will be referred to as a C++-stylecomment, tells the compiler to ignore everything that follows this comment, untilthe end of the line.</P><P>The slash-star comment mark tells the compiler to ignore everything that followsuntil it finds a star-slash (*/) comment mark. These marks will be referred to asC-style comments. Every /* must be matched with a closing */.</P><P>As you might guess, C-style comments are used in the C language as well, but C++-stylecomments are not part of the official definition of C.</P><P>Many C++ programmers use the C++-style comment most of the time, and reserve C-stylecomments for blocking out large blocks of a program. You can include C++-style commentswithin a block &quot;commented out&quot; by C-style comments; everything, includingthe C++-style comments, is ignored between the C-style comment marks.<H4 ALIGN="CENTER"><A NAME="Heading11"></A><FONT COLOR="#000077">Using Comments</FONT></H4><P>As a general rule, the overall program should have comments at the beginning,telling you what the program does. Each function should also have comments explainingwhat the function does and what values it returns. Finally, any statement in yourprogram that is obscure or less than obvious should be commented as well.</P><P>Listing 2.3 demonstrates the use of comments, showing that they do not affectthe processing of the program or its output.</P><P><A NAME="Heading12"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 2.3. HELP.CPPdemonstrates comments</B></FONT><FONT SIZE="2" COLOR="#000077"><B>.</B></FONT><FONTCOLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1: #include &lt;iostream.h&gt;2:3: int main()4: {5:  /* this is a comment6:  and it extends until the closing7:  star-slash comment mark */8:    cout &lt;&lt; &quot;Hello World!\n&quot;;9:    // this comment ends at the end of the line10:   cout &lt;&lt; &quot;That comment ended!\n&quot;;11:12:  // double slash comments can be alone on a line13: /* as can slash-star comments */14:     return 0;15: }Hello World!That comment ended!</FONT></PRE><P>The comments on lines 5 through 7 are completely ignored by the compiler, as <BR>are the comments on lines 9, 12, and 13. The comment on line 9 ended with the <BR>end of the line, however, while the comments on lines 5 and 13 required a closingcomment mark.<H4 ALIGN="CENTER"><A NAME="Heading14"></A><FONT COLOR="#000077">Comments at theTop of Each File</FONT></H4><P>It is a good idea to put a comment block at the top of every file you write. Theexact style of this block of comments is a matter of individual taste, but everysuch header should include at least the following information:<UL>	<LI>The name of the function or program.	<P>	<LI>The name of the file.	<P>	<LI>What the function or program does.	<P>	<LI>A description of how the program works.	<P>

⌨️ 快捷键说明

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