6 函数
6.1 概述
作用: 将经常使用的一段代码封装起来,减少重复代码
一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能
6.2 函数的定义
一般函数定义有5个主要步骤
- 返回值类型
- 函数名
- 参数列表
- 函数体语句
- return表达式
语法
//返回值类型 函数名(参数列表)
int isprime(int n)
{
//函数体语句
//return表达式
return 0;
}
- 实例1
#include<bits/stdc++.h>
using namespace std;
int add(int a , int b)
{
int sum = a+b;
return sum;
}
int main()
{
int num1,num2;
scanf("%d %d",&num1,&num2);
printf("%d",add(num1,num2));
system("pause");
return(0);
}
a,b 我们可以称为形参,num1,num2 我们可以称为实参,函数调用本质是将实参传递给形参并进行函数运算,返回return值
6.3 函数的调用
功能: 使用定义好的函数
语法:函数名(参数)
6.4 值传递
- 值传递就是函数调用时实参将数值转递给形参
- 值传递时,形参发生变化,并不会影响实参
#include<bits/stdc++.h>
using namespace std;
void swap(int a,int b) //在无需返回值时,可以输入viod类型
{
int temp = a;
a = b;
b =temp;
cout << "交换后:"<<a <<" "<<b <<endl;
return;
}
int main()
{
int i1 = 4;
int i2 = 5;
cout <<"交换前:"<<i1<<" "<<i2<<endl;
swap(4,5);
}
Note
在值传递的时候,为实参和形参分别分配内存空间,将实参的内存传递给形参,进而使用形参的内存去执行函数,实参的内存不会发生改变
6.5 函数的常见样式
- 无参无返
- 有参无返
- 无参有返
- 有参有返
- 实例
#include<bits/stdc++.h>
using namespace std;
//1.无参无返
void test_01()
{
cout << "跟你爆了"<<endl;
return;
}
//2.有参无返
void test_02(int a)
{
cout << a*a <<endl;
return;
}
//3.无参有返
int test_03()
{
return 1000;
}
//4.有参有返
int test_04(int k)
{
return (k*2)+k;
}
int main()
{
test_01();
test_02(4);
int num1 = test_03();
cout<<num1<<endl;
int m = test_04(4);
cout <<m <<endl;
system("pause");
return(0);
}
6.6 函数的声明
作用: 告诉编译器函数名称及如何调用函数,函数的实际主体可以单独定义
- 函数可以声明多次,但函数的定义只能有一次
示例:
#include<bits/stdc++.h>
using namespace std;
//声明
int max01(int a,int b);
int main()
{
int t = max01(5,6);
cout << t << endl;
system("pause");
return(0);
}
//定义
int max01(int a,int b)
{
return a>b ? a : b;
}
6.7 函数的分文件填写
作用: 让代码结构更加清晰
函数分文件编写一般有4个步骤
- 创建后缀名为.h的头文件
- 创建后缀名为.cpp的源文件
- 在头文件中书写函数的声明
- 在源文件中书写函数的定义
示例
//head.h
#include<bits/stdc++.h>
using namespace std;
void swap(int a,int b);
//fun.cpp
#include<bits/stdc++.h>
#include "head.h"
using namespace std;
void swap(int a,int b)
{
int temp = a;
a = b;
b = temp;
cout << a <<" "<<b << endl;
}
//test.cpp
#include<bits/stdc++.h>
using namespace std;
#include "head.h"
int main()
{
swap(4,5);
return(0);
}
Important
在VScode中,C++编译只对test.cpp中的main函数进行编译,无法连接到我们的fun.cpp文件
- ==解决方法:将头文件的文件目录复制到 .vscode目录下的tasks.json的”args”: 的”${file}“下面即可==
- 注意复制的单斜杠要改为多斜杠