函数
将经常使用的一段代码封装起来,避免重复代码
函数定义与调用
5步
1、返回值类型
2、函数名
3、参数列表
4、函数体语句
5、return表达式
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
值传递
函数调用时,是实参 将 数值传给 形参
形参变化 不会 影响实参
函数常见样式
//无参无返
void a1()
{
cout << "asd" << endl;
}
//有参无返
void a2(int a)
{
cout << a << endl;
}
//无参有返
int a3()
{
int a = 0;
return a;
}
//有参有返
int a4(int a ,int b)
{
int c = a + b;
return c;
}
函数份文件编写
4步
1、创建后缀名为 .h 的头文件
2、创建后缀名为.cpp的源文件
3、在头文件中写函数的声明
4、在源文件中写函数的定义
#include <iostream>
using namespace std;
//3、在头文件中写函数的声明
void swap(int a, int b);
#include "swap.h"
//4、在源文件中写函数的定义
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
#include <iostream>
#include "swap.h"
using namespace std;
#define week 7
#include <string>
int main()
{
int a = 1;
int b = 2;
swap(a, b);
system("pause");
return 0;
}
函数声明
利用函数声明,提前告诉函数存在
//函数声明
int a4(int a, int b);
int main()
{
int a = 1;
int b = 2;
int b4 = a4(a, b);
cout << b4 << endl;
system("pause");
return 0;
}
int a4(int a, int b)
{
int c = a + b;
return c;
}