函数
概述
作用:讲一段经常使用的代码封装起来,减少重复代码
一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能
函数的定义
函数的定义一般主要由五个步骤:
- 返回值类型
- 函数名
- 参数列表
- 函数条件语句
- return表达式
语法:
返回值类型 函数名 (参数列表)
{
函数条件语句
return 返回值;
}
函数的调用
功能:使用定义好的函数
语法:函数名(参数)
示例:
#include<iostream>;
using namespace std;
int add(int num1, int num2)
{
return num1 + num2;
}
int main() {
int num1 = 0;
int num2 = 0;
cout << "请输入您要计算的第一个数字:" << endl;
cin >> num1;
cout << "请输入您要计算的第二个数字:" << endl;
cin >> num2;
cout << add(num1, num2) << endl;
system("pause");
return 0;
}
总结:函数定义里小括号内称为形参,函数调用时传入的参数称为实参
值传递
- 所谓值传递,就是函数调用时实参将数值传入给形参
- 传值递时,如果形参发生,并不会影响实参
示例:
void swap(int num1, int num2)
{
cout << "交换前:" << endl;
cout << "num1:" << num1 << endl;
cout << "num2:" << num2 << endl;
int a = 0;
a = num1;
num1 = num2;
num2 = a;
cout << "交换后:" << endl;
cout << "num1:" << num1 << endl;
cout << "num2:" << num2 << endl;
return;
}
int main() {
int num1 = 0;
int num2 = 0;
cout << "请输入您要计算的第一个数字:" << endl;
cin >> num1;
cout << "请输入您要计算的第二个数字:" << endl;
cin >> num2;
swap(num1, num2);
cout << num1 << endl;
cout << num2 << endl;
system("pause");
return 0;
}
函数的常见样式
常见的函数样式有4种
- 无参无返
- 有参吴返
- 无参有返
- 有参有返
示例:
//1.无参函数
void test1() {
cout << "我是一个无参函数" << endl;
}
//2.有参无返
void test2(int num1, int num2)
{
cout << "交换前:" << endl;
cout << "num1:" << num1 << endl;
cout << "num2:" << num2 << endl;
int a = 0;
a = num1;
num1 = num2;
num2 = a;
cout << "交换后:" << endl;
cout << "num1:" << num1 << endl;
cout << "num2:" << num2 << endl;
return;
}
//3.无参有返
int test3()
{
cout << "这是无参有返" << endl;
return 2;
}
//有参有返
int test4(int num1, int num2)
{
return num1 + num2;
}
int main(){
test1();
test2(2, 22);
int a = test3();
int b = test4(4, 6);
cout << a << endl;
cout << b << endl;
system("pause");
return 0;
}
函数的声明
作用:告诉编译器函数名称及如何调用函数,函数的实现主体可以单独定义
- 函数的声明可以多次,但是函数的定义只能有一次
示例:
#include<iostream>
using namespace std;
//函数的声明
int test(int num12, int num2);
int main() {
int c = test(4,6);
cout << c << endl;
system("pause");
return 0;
}
int test(int num1, int num2)
{
return num1 > num2 ? num1 : num2;
}
函数的分文件编写
作用:让代码结构更加清晰
韩式分文件别写一般有四个步骤
- 创建后缀名为.h的头文件
- 创建后缀名为.cpp的源文件
- 在头文件中写函数的声明
- 在源文件中写函数的定义