《皮德常C++设计》Chapter-3答辩.pptVIP

  • 10
  • 0
  • 约1.37万字
  • 约 63页
  • 2016-12-26 发布于湖北
  • 举报
* 必须借助外部的力量来实现函数值的返回。例如:创建一个临时变量,将临时变量的值送给指定的变量。 * 如果函数具有多个引用参数,每个引用变量前加符号。 void addThree ( int , int , int , int ) ; void addThree ( int sum, int n1, int n2, int n3) { cout 请输入三个整形值: ; cin n1 n2 n3 ; sum = n1 + n2 + n3 ; } 思考:如果函数f的形参是引用,主调函数m在调用f时,实参是一个值,可以吗? 3.7 引用作参数 * 3.8 函数重载 程序中定义多个函数,函数的名字相同,但参数的类型或个数不完全相同。 int square ( int number ) { return number * number ; } double square ( double number ) { return number * number ; } int main ( ) { int userInt ; double userDouble ; cin userInt userDouble ; cout square(userInt) 和 square(userDouble ); } * 注意1:不能采用函数返回值的类型来区别重载: int square( int ) ; double square( int ) ; 注意2:C++在进行函数调用时,不仅靠函数名识别函数,而且还要看参数列表。 3.8 函数重载 【例3.11】计算员工的周薪。 void getChoice ( char ) ; double calcWeeklyPay ( int , double ) ; double calcWeeklyPay ( double ) ; int main ( ) { char selection ; int worked ; double rate , yearly ; cout 请选择计算工资的方式\n ; cout (H) 计算计时工资 \n ; cout (S) 计算员工的工资\n ; getChoice( selection ) ; 3-11.cpp switch( selection) { case H : case h : cout 已经工作多少小时? ; cin worked ; cout 每小时的报酬是多少? ; cin rate ; cout 毛收入: calcWeeklyPay(worked, rate ) ; break ; case S : case s : cout 年薪为多少? ; cin yearly ; cout 本周毛收入: calcWeeklyPay(yearly) ; break ; } return 0; } // 要求用户输入字符 H、h 或 S、s void getChoice ( char letter) { do { cout 请输入 H 或 S: ; cin letter ; } while(letter!= H letter != h letter!= S letter != s) ; } double calcWeeklyPay ( int hours, double payRate ) { return hours * payRate ; } double calcWeeklyPay ( double annSalary ) { return annSalary / 52.0 ; } * 3.9 函数模板 模板:函数和类模板。 函数模板简化重载。编译器遇到函数调用时,将根据实参类型和函数模板一起产生函数代码。 函数模板并不是真正意义上的函数,定义形式: template 类型参数表 返回值类型 函数名 ( 形式参数表 )

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档