




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、11/29/2021C+程序设计 教师:1Chapter 7. nFunctions11/29/2021C+程序设计 教师:2Functionsnevery C+ program must have a function called main nprogram execution always begins with function main nany other functions are subprograms and can be called 11/29/2021C+程序设计 教师:3Function CallsOne function calls another by using
2、 the name of the called function next to ( ) enclosing an argument list.A function call temporarily transfers control from the calling function to the called function.11/29/2021C+程序设计 教师:4 FunctionName ( Argument List )The argument list is a way for functions to communicate with each other by passin
3、g information.The argument list can contain 0, 1, or more arguments, separated by commas, depending on the function. Function Call Syntax11/29/2021C+程序设计 教师:5Two Parts of Function Definitionint Cube ( int n )heading body return n * n * n ;11/29/2021C+程序设计 教师:6What is in a prototype? A prototype look
4、s like a heading but must end with a semicolon; and its parameter list just needs to contain the type of each parameter. int Cube( int ); / prototype11/29/2021C+程序设计 教师:7When a function is called,temporary memory is set up ( for its value parameters and any local variables, and also for the function
5、s name if the return type is not void). Then the flow of control passes to the first statement in the functions body. The called functions body statements are executed until one of these occurs: return statement (with or without a return value),or, closing brace of function body.Then control goes ba
6、ck to where the function was called.11/29/2021C+程序设计 教师:8#include int Cube ( int ) ;/ prototypeusing namespace std; void main ( ) int yourNumber ; arguments int myNumber ; yourNumber = 14 ; myNumber = 9 ; cout “My Number = “ myNumber ; cout “its cube is “ Cube (myNumber) endl ; cout “Your Number = “
7、 yourNumber ; cout “its cube is “ Cube (yourNumber) endl ;11/29/2021C+程序设计 教师:9A C+ function can returnnin its identifier at most 1 value of the type which was specified (called the return type) in its heading and prototype nbut, a void-function cannot return any value in its identifier 11/29/2021C+
8、程序设计 教师:10return;nis valid only in the body block of void functions ncauses control to leave the function and immediately return to the calling block leaving any subsequent statements in the function body unexecuted 11/29/2021C+程序设计 教师:11Header files contain declarations of nnamed constants likecons
9、t int INT_MAX = 32767;nfunction prototypes likefloat sqrt( float );nclasses likestring, ostream, istreamnobjects likecin, cout 11/29/2021C+程序设计 教师:12Program with Several FunctionsSquare functionCube functionfunction prototypesmain function11/29/2021C+程序设计 教师:13Value-returning Functions#include int S
10、quare ( int ) ; / prototypesint Cube ( int ) ;using namespace std; int main ( ) cout “The square of 27 is “ Square (27) endl; / function call cout “The cube of 27 is “ Cube (27) endl; / function call return 0;11/29/2021C+程序设计 教师:14Rest of Programint Square ( int n )/ header and body return n * n;int
11、 Cube ( int n )/ header and body return n * n * n;11/29/2021C+程序设计 教师:15Parameter Listnis the means used for a function to share information with the block containing the call 11/29/2021C+程序设计 教师:16Classified by LocationAlways appear in a function call within the calling block.Always appear in the f
12、unction heading, or function prototype.Arguments Parameters11/29/2021C+程序设计 教师:17Some C+ Textsnuse the term “actual parameters” for arguments nthose books then refer to parameters as “formal parameters”11/29/2021C+程序设计 教师:18Value Parameter Reference ParameterThe value (25) of theargument is passed t
13、o the function when it is called.The memory address (4000)of the argumentis passed to the function when it is called.2540004000ageIn this case, the argument can be a variable identifier,constant,or expression.In this case, the argumentmust be a variableidentifier. Argumentin Calling Block11/29/2021C
14、+程序设计 教师:19By default, parameters (of simple types like int, char, float, double) are always value parameters, unless you do something to change that. To get a reference parameter you need to place & after the type in the function heading and prototype.11/29/2021C+程序设计 教师:20When to Use Reference
15、 Parameters nreference parameters should be used when you want your function to give a value to, or change the value of, a variable from the calling block11/29/2021C+程序设计 教师:21MAIN PROGRAM MEMORY 254000ageIf you pass only a copy of 25 to a function, it is called “pass-by-value” and the function will
16、 not be able to change the contents of age. It is still 25 when you return.11/29/2021C+程序设计 教师:22MAIN PROGRAM MEMORYBUT, if you pass 4000, the address of age to a function, it is called “pass-by-reference” and the function will be able to change the contents of age. It could be 23 or 90 when you ret
17、urn. 254000age11/29/2021C+程序设计 教师:23Pass-by-reference is also called . . . npass-by-address, ornpass-by-location 11/29/2021C+程序设计 教师:24Example of Pass-by-Reference We want to find 2 real roots for a quadratic equation with coefficients a,b,c. Write a prototype for a void function named GetRoots( ) w
18、ith 5 parameters. The first 3 parameters are type float. The last 2 are reference parameters of type float.11/29/2021C+程序设计 教师:25void GetRoots ( float , float , float , float& , float& );Now write the function definition using this information. This function uses 3 incoming values a, b, c fr
19、om the calling block. It calculates 2 outgoing values root1 and root2 for the calling block. They are the 2 real roots of the quadratic equation with coefficients a, b, c. / prototype 11/29/2021C+程序设计 教师:26void GetRoots( float a, float b, float c, float& root1, float& root2) float temp; / lo
20、cal variable temp = b * b - 4.0 * a * c; root1 = (-b + sqrt(temp) ) / ( 2.0 * a ); root2 = (-b - sqrt(temp) ) / ( 2.0 * a ); return;Function Definition11/29/2021C+程序设计 教师:27#include #include #include void GetRoots(float, float, float, float&, float&);using namespace std;void main ( ) ifstrea
21、m myInfile; ofstream myOutfile; float a, b, c, first, second; int count = 0; . / open files while ( count a b c; GetRoots(a, b, c, first, second); /call myOutfile a b c first second endl; count+ ; / close files . 11/29/2021C+程序设计 教师:28Pass-by-valueCALLINGBLOCK FUNCTION CALLED“incoming”value ofargume
22、nt11/29/2021C+程序设计 教师:29Pass-by-referenceCALLINGBLOCK FUNCTION CALLED“incoming”original value ofargument“outgoing”changed value ofargumentOR,11/29/2021C+程序设计 教师:30Pass-by-referenceCALLINGBLOCK FUNCTION CALLED argument has no value yet when call occurs“outgoing”new value ofargument11/29/2021C+程序设计 教师
23、:31Data Flow Determines Passing-Mechanism p254Incoming /* in */ Pass-by-valueOutgoing /* out */ Pass-by-referenceIncoming/outgoing Pass-by-reference /* inout */Parameter Data Flow Passing-Mechanism11/29/2021C+程序设计 教师:32C+ 基础知识引用nC+中使用引用建立变量或对象的别名。n引用分为:引用参数、返回引用以及独立引用。11/29/2021C+程序设计 教师:33C+ 基础知识引用
24、n#includenvoid swap(int &x, int &y)nint tmp;ntmp=x;nx=y;ny=tmp;nnvoid main()nint a=1,b=2;ncoutendlold a: a old b: b;nswap(a,b);ncoutendlnew a: a new b: b;ncoutendl;n引用参数11/29/2021C+程序设计 教师:34C+ 基础知识引用n#includenchar s=Hello world;nchar &replace(int i) nreturn si;nnvoid main()nreplace(5)=X
25、;ncoutsendl;n返回引用11/29/2021C+程序设计 教师:35C+ 基础知识引用n#includenvoid main()nint a=1,b=2;nint &ref=a; nref=10;ncoutnew a: aendl;n独立引用11/29/2021C+程序设计 教师:36C+ 基础知识引用n说明引用时,独立引用必须初始化。说明引用时,独立引用必须初始化。n一旦初始化,引用就不能重新赋值。一旦初始化,引用就不能重新赋值。11/29/2021C+程序设计 教师:37QuestionsnWhy is a function used for a task?To cut
26、down on the amount of detail in your main program (encapsulation).nCan one function call another function?YesnCan a function even call itself?Yes, that is called recursion. It is very useful and requires special care in writing.11/29/2021C+程序设计 教师:38More QuestionsnDoes it make any difference what na
27、mes you use for parameters?NO. Just use them in function body.nDo parameter names and argument names have to be the same?NO.11/29/2021C+程序设计 教师:39Write prototype and function definition forna void function called GetRating( ) with one reference parameter of type char nthe function repeatedly prompts
28、 the user to enter a character at the keyboard until one of these has been entered: E, G, A, P to represent Excellent, Good, Average, Poor 11/29/2021C+程序设计 教师:40void GetRating( char& ); / prototype void GetRating (char& letter)cout “Enter employee rating.” endl; cout letter; while ( (letter
29、!= E) & (letter != G) & (letter != A) & (letter != P) )cout letter;11/29/2021C+程序设计 教师:41What is a driver?nIt is a short main program whose only purpose is to call a function you wrote, so you can determine whether it meets specifications and works as expected.nwrite a driver for functio
30、n GetRating( )11/29/2021C+程序设计 教师:42#include void GetRating( char& ); / prototypeusing namespace std;int main( ) char rating; rating = X;GetRating(rating);/ callcout “That was rating = “ rating endl; return 0;11/29/2021C+程序设计 教师:43void GetRating (char& letter)cout “Enter employee rating.” en
31、dl; cout letter; while ( (letter != E) & (letter != G) & (letter != A) & (letter != P) )cout letter;11/29/2021C+程序设计 教师:44Preconditions and Postconditionsnthe precondition is an assertion describing everything that the function requires to be true at the moment the function is invoked nt
32、he postcondition describes the state at the moment the function finishes executing nthe caller is responsible for ensuring the precondition, and the function code must ensure the postcondition FOR EXAMPLE . . .11/29/2021C+程序设计 教师:45Function with Postconditionsvoid GetRating ( /* out */ char& let
33、ter)/ Precondition: None/ Postcondition: User has been prompted to enter a character/ & letter = one of these input values: E,G,A, or P cout “Enter employee rating.” endl; cout letter; while ( (letter != E) & (letter != G) & (letter != A) & (letter != P) )cout letter;11/29/2021C+程序设计
34、 教师:46Function with Preconditions and Postconditionsvoid GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& root1, /* out */ float& root2 )/ Precondition: a, b, and c are assigned/ & a != 0 & b*b - 4*a*c =0/ Postcondition: root1 and root2 are assigned /
35、& root1 and root2 are roots of quadratic with coefficients a, b, c float temp; temp = b * b - 4.0 * a * c; root1 = (-b + sqrt(temp) ) / ( 2.0 * a ); root2 = (-b - sqrt(temp) ) / ( 2.0 * a ); return;11/29/2021C+程序设计 教师:47Function with Preconditions and Postconditionsvoid Swap( /* inout */ int&
36、; firstInt, /* inout */ int& secondInt )/ Precondition: firstInt and secondInt are assigned/ Postcondition: firstInt = secondIntentry / & secondInt = firstIntentry int temporaryInt ; temporaryInt = firstInt ; firstInt = secondInt ; secondInt = temporaryInt ; 11/29/2021C+程序设计 教师:48assert func
37、tion P265n#include nassert( studentCount 0 );naverage = sumOfScores / studentCount;11/29/2021C+程序设计 教师:49TRUE/FALSE It is possible to supply different argument names every time a function is called. A)TrueB)False11/29/2021C+程序设计 教师:50TRUE/FALSEvTRUE11/29/2021C+程序设计 教师:51TRUE/FALSE If a C+ function d
38、oes not use arguments, you still must put parentheses around the empty argument list. A)TrueB)False11/29/2021C+程序设计 教师:52TRUE/FALSEvTRUE11/29/2021C+程序设计 教师:53TRUE/FALSE Using a pass by reference, passing an int argument to a float parameter is acceptable to the compiler but may produce incorrect res
39、ults. A)TrueB)False11/29/2021C+程序设计 教师:54TRUE/FALSEvFALSE11/29/2021C+程序设计 教师:55TRUE/FALSE In C+, a function definition may have another function definition nested within it. A)TrueB)False11/29/2021C+程序设计 教师:56TRUE/FALSEvFALSE11/29/2021C+程序设计 教师:57TRUE/FALSE If there are several items in a parameter
40、list, the compiler matches the parameters and arguments by their relative positions in the parameter and argument lists. A)TrueB)False11/29/2021C+程序设计 教师:58TRUE/FALSEvTRUE11/29/2021C+程序设计 教师:59TRUE/FALSE In C+, a function can be declared several times but can be defined only once. A)TrueB)False11/29
41、/2021C+程序设计 教师:60TRUE/FALSEvTRUE11/29/2021C+程序设计 教师:61CHOICE Which of the following is not a reason why programmers write their own functions? A)to help organize and clarify programs B)to make programs execute faster than they would with sequential flow of control C)to allow the reuse of the same co
42、de (function) within the same program D)to allow the reuse of the same code (function) within another program 11/29/2021C+程序设计 教师:62CHOICEv B11/29/2021C+程序设计 教师:63CHOICE In C+, a function prototype is A)a declaration but not a definition. B)a definition but not a declaration. C)both a declaration an
43、d a definition. D)neither a declaration nor a definition. 11/29/2021C+程序设计 教师:64CHOICEvA11/29/2021C+程序设计 教师:65CHOICE Given the function prototype void Fix( int&, float );which of the following is an appropriate function call? (someInt is of type int, and someFloat is of type float.) A)Fix(24, 6.
44、85); B)someFloat = 0.3 * Fix(someInt, 6.85); C)Fix(someInt + 5, someFloat); D)a and c above E)none of the above 11/29/2021C+程序设计 教师:66CHOICEv E11/29/2021C+程序设计 教师:67CHOICE A function SomeFunc has two parameters, alpha and beta, of type int. The data flow for alpha is one-way, into the function. The
45、data flow for beta is two-way, into and out of the function. What is the most appropriate function heading for SomeFunc? A)void SomeFunc( int alpha, int beta ) B)void SomeFunc( int& alpha, int beta ) C)void SomeFunc( int alpha, int& beta ) D)void SomeFunc( int& alpha, int& beta ) 11/
46、29/2021C+程序设计 教师:68CHOICEv C11/29/2021C+程序设计 教师:69CHOICE Which of the following statements about value parameters is true? A)The callers argument is never modified by execution of the called function. B)The parameter is never modified by execution of the called function. C)The callers argument must be a variable. D)The callers argument cannot have a Boolean value. E)b and c above 11/29/2021C+程序设计 教师:70CHOICEv A11/29/2021C+程序设计 教师:71CHOIC
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 公司签约劳务合同标准文本
- 临时劳务维修合同标准文本
- 个人租地协议合同标准文本
- 仓库发货员合同标准文本
- 内墙装饰工程合同标准文本
- 会所店面转让合同标准文本
- 农场厂房建设合同标准文本
- 业务合作合同标准文本复制
- 个人装修装饰合同标准文本
- 公路投标合同标准文本
- 开封滨润新材料有限公司 20 万吨年聚合氯化铝项目环境影响报告
- 《油气行业数字化转型白皮书》
- 读《传媒的四种理论》
- 色彩基础知识课件-PPT
- GB/T 13954-1992特种车辆标志灯具
- 纤维素酶活性的测定
- 2022“博学杯”全国幼儿识字与阅读大赛选拔试卷
- 2022年老年人健康管理工作总结
- ICU轮转护士考核试卷试题及答案
- 监理规划报审
- 《铸件检验记录表》
评论
0/150
提交评论