? ? ? ? 作用:将一段经常使用的代码封装起来,减少重复代码,一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能。
1. 定义
定义:
- 返回值类型
- 函数名
- 参数列表
- 函数体语句
- return表达式
语法: 返回值类型 函数名(参数1, 参数2, …) { 函数体语句 return 表达式 }
#include<iostream>
using namespace std;
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
int main()
{
cout << add(3, 4) << endl;
system("pause");
return 0;
}
2. 函数的调用
#include<iostream>
using namespace std;
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
int main()
{
int a = 10;
int b = 20;
int c = add(a, b);
cout << c << endl;
a = 100;
b = 500;
c = add(a,b);
cout << c << endl;
system("pause");
return 0;
}
3. 值传递
- 含义:所谓值传递,就是函数调用时将实参数值传入给形参
- 值传递时,如果形参发生变化,并不会影响实参
#include<iostream>
using namespace std;
void swap(int num1, int num2)
{
cout << "before swap:" << endl;
cout << "num1:" << num1 << endl;
cout << "num2:" << num2 << endl;
int temp = num1;
num1 = num2;
num2 = temp;
cout << "after swap:" << endl;
cout << "num1:" << num1 << endl;
cout << "num2:" << num2 << endl;
}
int main()
{
int a = 10;
int b = 20;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
swap(a, b);
cout << "a:" << a << endl;
cout << "b:" << b << endl;
system("pause");
return 0;
}
4. 函数的常见样式
#include<iostream>
using namespace std;
void test01()
{
cout << "test01" << endl;
}
void test02(int a)
{
cout << "test02:" << a << endl;
}
int test03()
{
cout << "test03" << endl;
return 250;
}
int test04(int b)
{
cout << "test03" << endl;
return b;
}
int main()
{
test01();
int a = 10;
test02(a);
test03();
int b = 23;
test04(b);
system("pause");
return 0;
}
5. 函数的声明
- 作用:告诉编译器函数名称以及如何调用函数,函数的实际主体可以单独定义
#include<iostream>
using namespace std;
int max(int a, int b);
int main()
{
int a = 10;
int b = 20;
cout << max(a, b) << endl;
system("pause");
return 0;
}
int max(int a, int b)
{
return a > b ? a : b;
}
6. 函数的分文件编写
步骤:
- 创建后缀名为.h的头文件
- 创建后缀名为.cpp的源文件
- 在头文件中写函数的声明
- 在源文件中写函数的定义
swap.h
#include<iostream>
using namespace std;
void swap(int a, int b);
swap.cpp
#include "swap.h"
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << a << endl;
cout << b << endl;
}
test.cpp
#include<iostream>
#include "swap.h"
using namespace std;
int main()
{
int a = 10;
int b = 20;
swap(a,b);
system("pause");
return 0;
}
|