- 1、函数
- 概述
- 函数的定义
- 语法
- 1.1 函数的调用
- 1.2 值传递
- 1.3 为什么值传递时,如果形参发生改变,并不会影响到实参?
- 1.4 函数的常见样式
- 1.5 函数的声明
- 1.6 函数的分文件编写
函数的定义作用:将一段经常使用的代码封装起来,减少重复代码
一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能
语法 1.1 函数的调用函数的定义一般主要有5个步骤:
1、返回值类型
2、函数名
3、参数表列
4、函数体语句
5、return表达式
功能:使用定义好的函数
语法:函数名(参数)
#includeusing namespace std; #include //使用string字符 //函数定义的时候,num1和num2并不是真实数据,只是一个形式参数,简称形参 int add(int num1, int num2) { int sum = 0; sum = num1 + num2; return sum; } int main() { //main函数调用add函数 int a = 10; int b = 20; int c=add(a, b); //a和b是真实的值,简称实参 //当调用函数的时候,实参的值会传递给形参 cout << c<< endl; system("pause");//按任意键继续 return 0;//返回退出值 }
输出:
301.2 值传递
所谓值传递就是函数调用时实参将数值传递给形参
值传递时,如果形参发生,并不会影响到实参
#includeusing namespace std; #include //使用string字符 //值传递 //定义函数,实现2个数字进行交换,当不需要返回值时,用void声明 void swap(int num1, int num2) { cout << "交换前的数值:" << endl; cout << "num1=" << num1 << endl; cout << "num2=" << num2 << endl; int temp = num1; num1 = num2; num2 = temp; cout << "交换后的数值:" << endl; cout << "num1=" << num1 << endl; cout << "num2=" << num2 << endl; } int main() { int a = 10; int b = 20; swap(a, b); system("pause");//按任意键继续 return 0;//返回退出值 }
输出:
交换前的数值: num1=10 num2=20 交换后的数值: num1=20 num2=101.3 为什么值传递时,如果形参发生改变,并不会影响到实参? 1.4 函数的常见样式
函数的常见样式通常有4种:
1、无参无返
2、无参有返
3、有参无返
4、有参有返
#includeusing namespace std; #include //使用string字符 //1、无参无返 void test01() { cout << "this is a test01" << endl; } //2、无参有返 int test03() { return 100; } //3、有参无返 void test02(int a) { cout << a << endl; } //4、有参有返 int test04(int a) { return a; } int main() { //1、无参无返 test01(); //2、无参有返 int num3 = test03(); cout << num3 << endl; //3、有参无返 int a = 10; test02(a); //4、有参有返 int num4 = test04(1000); cout << num4 << endl; system("pause");//按任意键继续 return 0;//返回退出值 }
输出:
this is a test01 100 10 10001.5 函数的声明
作用:告诉编译器函数名称及如何调用函数。函数的实际主体可以单独定义。
注意:函数的声明可以有多次,但函数的定义的只能有一次。
#includeusing namespace std; #include //使用string字符 //函数的声明,提前告诉编译器函数的存在 //函数的声明可以有多次,但函数的定义只能有一次 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) { if (a > b) { return a; } else { return b; } }
输出:
201.6 函数的分文件编写
作用:让代码结构更加清晰
函数的分文件编写一般有4个步骤:
1、创建后缀名为.h的头文件,如下图:
2、创建后缀名为.cpp的源文件,如下图:
3、在头文件中写函数的声明
//函数的声明 void swap(int a, int b); #includeusing namespace std;
4、在源文件定义函数
#include "swap.h" //""表示这是我们自己定义的函数
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
5、然后在我们要调用的文件上面添加#include “swap.h”就能调用swap.cpp文件了,
#includeusing namespace std; #include //使用string字符 #include "swap.h" int main() { int a = 10; int b = 20; swap(a, b); system("pause");//按任意键继续 return 0;//返回退出值 }
注意:
1、为了使源文件和头文件有连接,在源文件上面添加头文件;
2、为了使cout能正常使用,应在头文件添加:
#include
using namespace std;



