6 函数
6.1 描述
函数作用:封装、代码重用。
6.2 函数的定义
返回值类型 函数名 (参数列表)
{
...
return 表达式
}
e:
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
6.3 函数的调用
函数名(参数)
e:
int a = 10;
int b = 10;
int sum = add(a,b);
6.4 值传递
函数调用时实际上是将实参的值传递给形参。 因此值传递时,形参的的变化不会影响实参。
6.5 函数的常见样式
6.6 函数的声明
声明作用:告诉编译器如何调用函数。 函数实际内容可以在后面单独定义。 e:
//声明
int max(int a, int b);
//定义
int max(int a, int b)
{
return a>b ? a : b;
}
6.7 函数的分文件编写
作用:让代码结构更清晰 分文件函数编写一般有4步:
- 创建后缀为.h的头文件
- 创建后缀为.cpp 的源文件
- 头文件写函数声明
- 源文件写函数定义
e:
//max.h
#include<iostream>
using namespace std;
int max(int a, int b);
//max.cpp 文件
#include max.h
int max(int a, int b){
return a>b ? a : b;
}
注意include自己的头文件,用的是"":
#include "max.h"
导入标准库的头文件,用的是<>
#include<iostream>
另外,源文件max.cpp
需要在开头#include "max.h"
与头文件建立关联。