目录
1.1 概述
作用:将一段经常使用的代码封装起来,减少重复代码的使用。
1.2 函数的定义
步骤:
1、函数返回值类型:一个函数可以返回一个值,在函数定义中;
2、函数名:给函数起个名称;
3、参数表列:使用该函数时,传入的数据;
4、函数体语句:大括号内的代码,函数内需要执行的语句;
5、return 表达式:和返回值类型挂钩,函数执行完后,返回相应的数据。
语法:
返回值类型 函数名(参数列表)
{
函数体语句
return 表达式
}
示例:
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
1.3 函数的调用
语法:函数名<参数>
示例:
形参和实参的介绍如注释
#include<iostream>
using namespace std;
//定义一个加法函数
//函数定义的时候,num1和num2并没有实际的数据,他们只是形式参数,简称形参
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
int main()
{
//函数的调用
int a = 2;
int b = 4;
//调用的语法:函数名称<参数>
//a和b成为实际参数,简称实参
//当函数调用时,实参的值将会传递给形参
int c = add(a, b);
cout << "c=" << c << endl;
system("pause");
return 0;
}
1.4 值传递
介绍:就是函数调用时实参将数值传递给形参,就是值传递。
值传递时如果形参发生变化并不会影响实参。
代码示例:
#include<iostream>
using namespace std;
//函数定义,实现两个数字惊醒交换函数
//如果函数不需要返回值,声明的时候可以写void
void huan(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;
//返回值不需要的时候可以不写return,或者写成return ;
}
int main()
{
int a = 2;
int b = 4;
cout << "形参数值改变前:" << endl;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
huan(a, b);//调用函数
cout << "形参数值改变后:" << endl;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
system("pause");
return 0;
}
1.5 函数的常见样式
可分为四种:
1、无参无返
2、有参无返
3、无参有返
4、有参有返
代码示例:
#include<iostream>
using namespace std;
//无参无返
void test1()
{
cout << "无参无返" << endl;
cout << "欢迎学习C++" << endl;
}
//有参无返
void test2(int a)
{
cout << "有参无返" << endl;
cout << "a=" << a << endl;
}
//无参有返
int test3()
{
cout << "无参有返" << endl;
return 9;
}
//有参有返
int test4(int c)
{
cout << "有参有返" << endl;
return 567;
}
int main()
{
//无参无返的函数调用
test1();
//有参无返的函数调用
test2(100);
//无参有返的函数调用
int b = test3();
cout << "b=" << b << endl;
//有参有返的函数调用
int num = test4(567);
cout << "num=" << num << endl;
system("pause");
return 0;
}
1.6 函数的声明
作用:告诉编译器函数的名称及如何调用函数,函数的实际主题可以单独定义。
函数的声明可以多次,但是函数的定义只能有一次。
1.7 函数的分文件编写
作用:让代码结构更加清晰。
一般分为四步:
1、创建后缀名为.h的头文件
2、创建后缀名为.cpp的源文件
3、在头文件中写函数的声明
4、在源文件中写函数的定义
代码如下:
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=" << a << endl;
cout << "b=" << b << endl;
}
main.cpp文件:
#include<iostream>
using namespace std;
#include"swap.h"
//void swap(int a, int b)
/*
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
*/
int main()
{
int a = 10;
int b = 20;
swap(a, b);
system("pause");
return 0;
}