作用:将一段常用的代码封装起来,减少重复代码;
函数定义5个步骤:返回值类型、函数名、参数列表、函数体语句、return表达式
int add(int num1,int num2){
int res = num1 + num2;
return res;
}
一、函数声明
通过函数声明,表明有这么一个函数存在:
#include<iostream>
using namespace std;
//函数声明,可以只声明参数的类型
//由于进行了函数声明,虽然max函数在主函数之后,此时仍然是可以被调用的
int max(int, int);
int main() {
int a = 1;
int b = 2;
int res = max(a, b);
cout << res << endl;
system("pause");
return 0;
}
//函数定义
int max(int a, int b) {
int res = a > b ? a : b;
return res;
}
函数可以声明多次,但是只可以定义一次。
二、函数的分文件编写
函数分文件编写一般有以下四个步骤:
作用:让代码结构更加清晰。
目录结构:
max.h
#include<iostream>
using namespace std;
int max(int, int);
second.cpp
#include "max.h"
int main() {
int a = 1;
int b = 2;
int res = max(a, b);
cout << res << endl;
system("pause");
return 0;
}
int max(int a, int b) {
int res = a > b ? a : b;
return res;
}
三。值传递和引用传递
1.值传递
什么是值传递?
在函数调用时将实参的值传递给形参;
有什么特点?
值传递时,如果形参发生变化,则不会影响原来实参的值。
#include <iostream>
using namespace std;
void swap(int num1, int num2) {
cout << "交换之前num1的值:" << num1 << endl;
cout << "交换之前num2的值:" << num2 << endl;
int tmp = num1;
num1 = num2;
num2 = tmp;
cout << "交换之后num1的值:" << num1 << endl;
cout << "交换之后num2的值:" << num2 << endl;
}
int main()
{
int a = 1;
int b = 2;
cout << "实参未传入之前a的值:" << a << endl;
cout << "实参未传入之前b的值:" << b << endl;
swap(a, b);
cout << "实参传入之后a的值:" << a << endl;
cout << "实参传入之后b的值:" << b << endl;
system("pause");
return 0;
}
输出:
2.引用传递
什么是引用传递?
在函数调用时将实参的引用(即指针)传递给形参;
引用传递的特点?
引用传递时,如果形参发生变化,则同时会影响原来实参的值。
#include <iostream>
using namespace std;
void swap(int* num1, int* num2) {
cout << "交换之前num1的值:" << *num1 << endl;
cout << "交换之前num2的值:" << *num2 << endl;
int tmp = *num1;
*num1 = *num2;
*num2 = tmp;
cout << "交换之后num1的值:" << *num1 << endl;
cout << "交换之后num2的值:" << *num2 << endl;
}
int main()
{
int a = 1;
int b = 2;
int* p1 = &a;
int* p2 = &b;
cout << "实参未传入之前a的值:" << a << endl;
cout << "实参未传入之前b的值:" << b << endl;
swap(p1, p2);
cout << "实参传入之后a的值:" << a << endl;
cout << "实参传入之后b的值:" << b << endl;
system("pause");
return 0;
}
输出: