📄 ch05.htm
字号:
<!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="ch04.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch04.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="ch06.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch06.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 5</A> <UL> <LI><A HREF="#Heading2">Functions</A> <UL> <LI><A HREF="#Heading3">What Is a Function?</A> <UL> <LI><A HREF="#Heading4">Figure 5.1.</A> </UL> <LI><A HREF="#Heading5">Declaring and Defining Functions</A> <UL> <LI><A HREF="#Heading6">Declaring the Function</A> <LI><A HREF="#Heading7">Function Prototypes</A> <UL> <LI><A HREF="#Heading8">Figure 5.2.</A> </UL> </UL> <LI><A HREF="#Heading9">Listing 5.1. A function declaration</A> <LI><A HREF="#Heading10">and the definition and use of that function.</A> <UL> <LI><A HREF="#Heading11">Defining the Function</A> <UL> <LI><A HREF="#Heading12">Figure 5.3.</A> </UL> </UL> <LI><A HREF="#Heading13">Functions</A> <LI><A HREF="#Heading14">Execution of Functions</A> <LI><A HREF="#Heading15">Local Variables</A> <LI><A HREF="#Heading16">Listing 5.2. The use of local variables and parameters</A><A HREF="#Heading17">.</A> <LI><A HREF="#Heading18">Global Variables</A> <LI><A HREF="#Heading19">Listing 5.3. Demonstrating global and local variables</A><A HREF="#Heading20">.</A> <LI><A HREF="#Heading21">Global Variables: A Word of Caution</A> <LI><A HREF="#Heading22">More on Local Variables</A> <LI><A HREF="#Heading23">Listing 5.4. Variables scoped within a block</A><A HREF="#Heading24">.</A> <LI><A HREF="#Heading25">Function Statements</A> <LI><A HREF="#Heading26">Function Arguments</A> <UL> <LI><A HREF="#Heading27">Using Functions as Parameters to Functions</A> </UL> <LI><A HREF="#Heading28">Parameters Are Local Variables</A> <LI><A HREF="#Heading29">Listing 5.5. A demonstration of passing by value</A><A HREF="#Heading30">.</A> <LI><A HREF="#Heading31">Return Values</A> <LI><A HREF="#Heading32">Listing 5.6. A demonstration of multiple return statements</A><A HREF="#Heading33">.</A> <LI><A HREF="#Heading34">Default Parameters</A> <LI><A HREF="#Heading35">Listing 5.7. A demonstration of default parameter values.</A> <LI><A HREF="#Heading36">Overloading Functions</A> <LI><A HREF="#Heading37">Listing 5.8. A demonstration of function polymorphism</A><A HREF="#Heading38">.</A> <LI><A HREF="#Heading39">Special Topics About Functions</A> <UL> <LI><A HREF="#Heading40">Inline Functions</A> </UL> <LI><A HREF="#Heading41">Listing 5.9. Demonstrates an inline function</A><A HREF="#Heading42">.</A> <UL> <LI><A HREF="#Heading43">Recursion</A> </UL> <LI><A HREF="#Heading44">Listing 5.10. Demonstrates recursion using the Fibonacci series</A><A HREF="#Heading45">.</A> <LI><A HREF="#Heading46">How Functions WorkA Look Under the Hood</A> <UL> <LI><A HREF="#Heading48">Levels of Abstraction</A> <LI><A HREF="#Heading49">Partitioning RAM</A> <UL> <LI><A HREF="#Heading50">Figure 5.4.</A> <LI><A HREF="#Heading51">Figure 5.5.</A> <LI><A HREF="#Heading52">Figure 5.6.</A> <LI><A HREF="#Heading53">Figure 5.7.</A> </UL> <LI><A HREF="#Heading54">The Stack and Functions</A> </UL> <LI><A HREF="#Heading55">Summary</A> <LI><A HREF="#Heading56">Q&A</A> <LI><A HREF="#Heading57">Workshop</A> <UL> <LI><A HREF="#Heading58">Quiz</A> <LI><A HREF="#Heading59">Exercises</A> </UL> </UL> </UL></UL><P><HR SIZE="4"><H2 ALIGN="CENTER"><A NAME="Heading1"></A><FONT COLOR="#000077">Day 5</FONT></H2><H2 ALIGN="CENTER"><A NAME="Heading2"></A><FONT COLOR="#000077">Functions</FONT></H2><P>Although object-oriented programming has shifted attention from functions andtoward objects, functions nonetheless remain a central component of any program.Today you will learn<UL> <LI>What a function is and what its parts are. <P> <LI>How to declare and define functions. <P> <LI>How to pass parameters into functions. <P> <LI>How to return a value from a function.</UL><H3 ALIGN="CENTER"><A NAME="Heading3"></A><FONT COLOR="#000077">What Is a Function?</FONT></H3><P>A function is, in effect, a subprogram that can act on data and return a value.Every C++ program has at least one function, <TT>main()</TT>. When your program starts,<TT>main()</TT> is called automatically. <TT>main()</TT> might call other functions,some of which might call still others.</P><P>Each function has its own name, and when that name is encountered, the executionof the program branches to the body of that function. When the function returns,execution resumes on the next line of the calling function. This flow is illustratedin Figure 5.1.<BR><BR><A NAME="Heading4"></A><A HREF="05zcp01.jpg" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/art/ch05/05zcp01.jpg"><FONT COLOR="#000077">Figure5.1.</FONT></A><FONT COLOR="#000077"> </FONT><FONT COLOR="#000000"><I>Illusrtationof flow</I></FONT></P><P>When a program calls a function, execution switches to the function and then resumesat the line after the function call. Well-designed functions perform a specific andeasily understood task. Complicated tasks should be broken down into multiple functions,and then each can be called in turn.</P><P>Functions come in two varieties: user-defined and built-in. Built-in functionsare part of your compiler package--they are supplied by the manufacturer for youruse.<H3 ALIGN="CENTER"><A NAME="Heading5"></A><FONT COLOR="#000077">Declaring and DefiningFunctions</FONT></H3><P>Using functions in your program requires that you first declare the function andthat you then define the function. The declaration tells the compiler the name, returntype, and parameters of the function. The definition tells the compiler how the functionworks. No function can be called from any other function that hasn't first been declared.The declaration of a function is called its prototype.<H4 ALIGN="CENTER"><A NAME="Heading6"></A><FONT COLOR="#000077">Declaring the Function</FONT></H4><P>There are three ways to declare a function:<UL> <LI>Write your prototype into a file, and then use the <TT>#include</TT> directive to include it in your program. <P> <LI>Write the prototype into the file in which your function is used. <P> <LI>Define the function before it is called by any other function. When you do this, the definition acts as its own declaration.</UL><P>Although you can define the function before using it, and thus avoid the necessityof creating a function prototype, this is not good programming practice for threereasons.</P><P>First, it is a bad idea to require that functions appear in a file in a particularorder. Doing so makes it hard to maintain the program as requirements change.</P><P>Second, it is possible that function <TT>A()</TT> needs to be able to call function<TT>B()</TT>, but function <TT>B()</TT> also needs to be able to call function <TT>A()</TT>under some circumstances. It is not possible to define function <TT>A()</TT> beforeyou define function <TT>B()</TT> and also to define function <TT>B()</TT> beforeyou define function <TT>A()</TT>, so at least one of them must be declared in anycase.</P><P>Third, function prototypes are a good and powerful debugging technique. If yourprototype declares that your function takes a particular set of parameters, or thatit returns a particular type of value, and then your function does not match theprototype, the compiler can flag your error instead of waiting for it to show itselfwhen you run the program.<H4 ALIGN="CENTER"><A NAME="Heading7"></A><FONT COLOR="#000077">Function Prototypes</FONT></H4><P>Many of the built-in functions you use will have their function prototypes alreadywritten in the files you include in your program by using <TT>#include</TT>. Forfunctions you write yourself, you must include the prototype.</P><P>The function prototype is a statement, which means it ends with a semicolon. Itconsists of the function's return type, name, and parameter list.</P><P>The parameter list is a list of all the parameters and their types, separatedby commas. Figure 5.2 illustrates the parts of the function prototype.<BR><BR><A NAME="Heading8"></A><A HREF="05zcp02.jpg" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/art/ch05/05zcp02.jpg"><FONT COLOR="#000077">Figure5.2.</FONT></A><FONT COLOR="#000077"> </FONT><I>Parts of a function prototype.</I><BR><BR>The function prototype and the function definition must agree exactly about the returntype, the name, and the parameter list. If they do not agree, you will get a compile-timeerror. Note, however, that the function prototype does not need to contain the namesof the parameters, just their types. A prototype that looks like this is perfectlylegal:</P><PRE><FONT COLOR="#0066FF">long Area(int, int);</FONT></PRE><P>This prototype declares a function named <TT>Area()</TT> that returns a <TT>long</TT>and that has two parameters, both integers. Although this is legal, it is not a goodidea. Adding parameter names makes your prototype clearer. The same function withnamed parameters might be</P><PRE><FONT COLOR="#0066FF">long Area(int length, int width);</FONT></PRE><P>It is now obvious what this function does and what the parameters are.</P><P>Note that all functions have a return type. If none is explicitly stated, thereturn type defaults to <TT>int</TT>. Your programs will be easier to understand,however, if you explicitly declare the return type of every function, including <TT>main()</TT>.Listing 5.1 demonstrates a program that includes a function prototype for the <TT>Area()</TT>function.</P><P><A NAME="Heading9"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 5.1. A functiondeclaration and the definition and use of that function.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 5.1 - demonstrates the use of function prototypes2:3: typedef unsigned short USHORT;4: #include <iostream.h>5: USHORT FindArea(USHORT length, USHORT width); //function prototype6:7: int main()8: {9: USHORT lengthOfYard;10: USHORT widthOfYard;11: USHORT areaOfYard;12:13: cout << "\nHow wide is your yard? ";14: cin >> widthOfYard;15: cout << "\nHow long is your yard? ";16: cin >> lengthOfYard;17:18: areaOfYard= FindArea(lengthOfYard,widthOfYard);19:20: cout << "\nYour yard is ";21: cout << areaOfYard;22: cout << " square feet\n\n";23: return 0;24: }25:26: USHORT FindArea(USHORT l, USHORT w)27: {28: return l * w;<TT>29: }</TT>Output: How wide is your yard? 100How long is your yard? 200Your yard is 20000 square feet</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The prototype for the <TT>FindArea()</TT>function is on line 5. Compare the prototype with the definition of the functionon line 26. Note that the name, the return type, and the parameter types are thesame. If they were different, a compiler error would have been generated. In fact,the only required difference is that the function prototype ends with a semicolonand has no body.<BR>Also note that the parameter names in the prototype are <TT>length</TT> and <TT>width</TT>,but the parameter names in the definition are <TT>l</TT> and <TT>w</TT>. As discussed,the names in the prototype are not used; they are there as information to the programmer.When they are included, they should match the implementation when possible. Thisis a matter of good programming style and reduces confusion, but it is not required,as you see here.</P><P>The arguments are passed in to the function in the order in which they are declaredand defined, but there is no matching of the names. Had you passed in <TT>widthOfYard</TT>,followed by <TT>lengthOfYard</TT>, the <TT>FindArea()</TT> function would have usedthe value in <TT>widthOfYard</TT> for <TT>length</TT> and <TT>lengthOfYard</TT> for<TT>width</TT>. The body of the function is always enclosed in braces, even whenit consists of only one statement, as in this case.<H4 ALIGN="CENTER"><A NAME="Heading11"></A><FONT COLOR="#000077">Defining the Function</FONT></H4><P>The definition of a function consists of the function header and its body. The
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -