自定义函式的目的 :
将程式码封装起来,实现快速重复使用。
函式定义的步骤:
1: 函式型别 (比如 int ,float,void(无型别,当不需要返回值时使用)
2 :函式名
3 : 引数列表 (形参)
4 :函式体语句(函式表示式)
5:return 表示式;
1 返回值型别 函式名 (引数列表) 2 { 3 4 函式体语句 5 6 return表示式 7 8 }
- 返回值型别 :一个函式可以返回一个值。在函式定义中
- 函式名:给函式起个名称
- 引数列表:使用该函式时,传入的资料
- 函式体语句:花括号内的程式码,函式内需要执行的语句
- return表示式: 和返回值型别挂钩,函式执行完后,返回相应的资料
需要返回值函式举例 :
1 #include <iostream> 2 using namespace std; 3 int a(int n1, int n2) 4 { 5 6 7 int sum = n1 + n2; 8 return sum; 9 /*假如不是sum,而是n1,或者其他的数(比如0)结果输出则会是n1或者其他的数,这个代表函式的输出值 */ 10 11 } 12 int main() 13 { 14 int n1 = 52; 15 int n2 = 25; 16 int b = a(n1, n2); 17 cout << b; 18 }
当返回 sum时结果 :
当返回 n1时结果:
不需要返回值函式举例 :
1 #include <iostream> 2 using namespace std; 3 void a(int n1, int n2) 4 { 5 int c = n1; 6 cout << "交换前n1为" << n1 << "," << "交换前n2为" << n2 << endl; 7 n1 = n2; 8 n2 = c; 9 cout << "交后n1为" << n1 << "," << "交换后前n2为" << n2 << endl; 11 } 12 int main() 13 { 14 int n1 = 52; 15 int n2 = 25; 16 a(n1, n2); 17 }//当没有返回值时函式会自动函式执行完后的n1,n2
值传递本质
使用者输入实参传递给形参时,本质上是把实参赋值给形参,所以当函式内部进入函式体表达式运算使得形参发生改变时,实参不会发生改变。
函式的常见样式 :
无参无返 :
1 #include <iostream> 2 using namespace std; 3 void a() 4 { 5 cout << " this is a " << endl; 6 } 7 int main() 8 { 9 a(); 10 }
有参无返 :
1 #include <iostream> 2 using namespace std; 3 void a(int b) 4 { 5 cout << " this is b " << b << endl; 6 } 7 int main() 8 { 9 a(200); 10 }
无参有返 :
1 #include <iostream> 2 using namespace std; 3 int a() 4 { 5 cout << " 这是无参有返的" << endl; //可去掉,只是标识一下 6 return 10000; 7 } 8 int main() 9 { 10 int b = a(); 11 cout << "b = " << b << endl; 12 }
有参有返 :
1 #include <iostream> 2 using namespace std; 3 int a(int b ) 4 { 5 cout << " 这是有参有返的" << endl; 6 return b; 7 } 8 int main() 9 { 10 int c = a(65); 11 cout << "c = " << c << endl; 12 }
函式的宣告与定义:
1 #include <iostream> 2 using namespace std; 3 int a(int b);//这是函式宣告,是告诉系统有这个函式,不要报错,只能写在需要输入实参的函式前面,可以重复宣告 4 int main() 5 { 6 int c = a(65); 7 cout << "c = " << c << endl; 8 } 9 int a(int b) 10 { 11 cout << " 这是有参有返的" << endl; 12 return b; 13 }//函式定义,定义函式执行的步骤与方式,函式定义可以放在任意的地方,即使这里也行,只能出现一次
函式的分档案编写:
意义:减少档案主体的程式码量,方便阅读
步骤 1
在标头档案中选择建立字尾为.h的新项目,然后在里面写函式宣告 :
步骤二 :
建立字尾为 .cpp 的原始档然后在里面写函式定义
步骤三 :
在正式档案中引用: