6.1概述
作用:将一个经常使用的代码封装起来,减少重复代码
一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能
6.2函数的定义
函数定义的5个步骤:
1、返回值类型
2、函数名
3、参数列表
4、函数体语句
5、return表达式
语法:
返回值类型 函数名 (参数列表)
{
函数体语句
return表达式
}
例如:
实现一个加法函数,功能室:传入两个整形数据,计算数据相加结果,并且返回
1、返回值 int
2、函数名 add
3、参数列表 (int num1,int num2)
4、函数体语句 int sum = num1 + num2;
5、return表达式 return sum;
6.3函数的调用
语法:函数名(参数)
//函数的定义
//语法;
//返回值类型 函数名 参数列表 函数体语句 return语句
//加法函数,实现两个整形相加,并且将相加的结果进行返回
int add(int num1, int num2)// num1,2没有实际数据,形式上的参数,简称“形参”
{
int sum = num1 + num2;
return sum;
}
int main()
{
//a b 有实际的值 称为“实参”
int a = 10;
int b = 20;
//函数调用语法 函数名 (参数)
int c = add(a, b);
cout << "c = " << c << endl;
system("pause");
return 0;
}
system("pause");
return 0;
}
6.4值传递
1、所谓值传递,就是函数调用时实参将数值传入给形参
2、值传递时,如果形参发生,并不会影响实参
//值传递
//定义函数,实现两个数字进行交换函数
//如果函数不需要返回值,声明的时候可以写void
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;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
//当我们做值传递的时候,函数的形参发生改变,并不会影响实参
swap(a, b);
cout << "a = " << a << endl; // a,b 不发生变化
cout << "b = " << b << endl;
6.5函数常见样式
常见函数样式有4种
1、无参无返
2、有参无返
3、无参有返
4、有参有返
//函数常见样式
//1、无参无返
void test01()
{
cout << " this is test01 " << endl;
}
//2、有参无返
void test02(int a)
{
cout << "this is test02 a = " << a << endl;
}
//3、无参有返
int test03()
{
cout << "this is test03" << endl;
return 1000;
}
//4、有参有返
int test04(int a)
{
cout << "this is test04 a = " << a << endl;
return a;
}
6.6函数声明
作用:告诉编译器函数名称及如何调用函数,函数的实际主体可以单独定义
函数的声明可以多次,但是函数的定义只能有一次
//函数的声明
//比较函数,实现两个整形数字进行比较,返回较大的值
//提前告诉编译器函数的存在,可以利用函数的声明
//函数的声明
int max(int a, int b)
{
int main()
{
int a = 10;
int b = 20;
int c = max(a, b);
cout << "c = " << c << endl;
system("pause");
return 0;
}
//函数的定义
int max(int a, int b)
{
return a > b ? a : b;
}
6.7 函数的分文件编写
作用:让代码结构更加清晰
函数分文件编写一般有4个步骤
1、创建后缀名为.h的头文件
2、创建后缀名为.cpp的源文件
3、在头文件中写函数的声明
4、在源文件中写函数的定义
1、主函数文件中
#include<iostream> using namespace std; #include "swap.h" int main() { int a = 10; int b = 20; swap(a, b); system("pause"); return 0; }
2、头文件.h
#include<iostream> using namespace std; //函数的声明 void swap(int a, int b);
3、源文件.cpp中
#include "swap.h" //函数的定义 void swap(int a, int b) { int temp = a; a = b; b = temp; cout << "a = " << a << endl; cout << "b = " << b << endl; }