概述
作用:将一段经常使用的代码封装起来,减少重复代码
一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能。
函数的定义
函数的定义一般主要有5个步骤:
1、返回值类型
2、函数名
3、参数表列
4、函数体语句
5、return 表达式
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27#include <iostream> using namespace std; //函数定义 int add(int num1, int num2) //定义中的num1,num2称为形式参数,简称形参 { int sum = num1 + num2; return sum; } int main() { int a = 10; int b = 10; //调用add函数 int sum = add(a, b);//调用时的a,b称为实际参数,简称实参 cout << "sum = " << sum << endl; a = 100; b = 100; sum = add(a, b); cout << "sum = " << sum << endl; system("pause"); return 0; }
值传递
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33#include <iostream> using namespace std; void swap(int num1, int num2) { cout << "交换前:" << endl; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; int temp = num1; num1 = num2; num2 = temp; cout << "交换后:" << endl; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; //return ; 当函数声明时候,不需要返回值,可以不写return } int main() { int a = 10; int b = 20; swap(a, b); cout << "mian中的 a = " << a << endl; cout << "mian中的 b = " << b << endl; system("pause"); return 0; }
函数的常见样式
常见的函数样式有4种
-
无参无返
-
有参无返
-
无参有返
-
有参有返
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30//函数常见样式 //1、 无参无返 void test01() { //void a = 10; //无类型不可以创建变量,原因无法分配内存 cout << "this is test01" << endl; //test01(); 函数调用 } //2、 有参无返 void test02(int a) { cout << "this is test02" << endl; cout << "a = " << a << endl; } //3、无参有返 int test03() { cout << "this is test03 " << endl; return 10; } //4、有参有返 int test04(int a, int b) { cout << "this is test04 " << endl; int sum = a + b; return sum; }
函数的声明
作用: 告诉编译器函数名称及如何调用函数。函数的实际主体可以单独定义。
-
函数的声明可以多次,但是函数的定义只能有一次
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23#include <iostream> using namespace std; //声明可以多次,定义只能一次 //声明 int max(int a, int b); int max(int a, int b); //定义 int max(int a, int b) { return a > b ? a : b; } int main() { int a = 100; int b = 200; cout << max(a, b) << endl; system("pause"); return 0; }
函数的分文件编写
作用:让代码结构更加清晰
函数分文件编写一般有4个步骤
-
创建后缀名为.h的头文件
-
创建后缀名为.cpp的源文件
-
在头文件中写函数的声明
-
在源文件中写函数的定义
最后
以上就是发嗲海燕最近收集整理的关于函数||值传递||函数的常见样式||函数的声明||函数的分文件编写的全部内容,更多相关函数||值传递||函数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复