- 函数-函数的定义
作用:将一段经常使用的代码封装起来,减少重复代码
一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能
函数的定义一般主要有5个步骤:
1.返回值类型(一个函数可以返回一个值,在函数定义中)
2.函数名(给函数起个名)
3.参数表列(使用该函数时,传入的数据)
4.函数体语句(花括号内的代码,函数内需要执行的语句)
5.return表达式(和返回值类型挂钩,函数执行完后,返回相应的数据)
语法:
返回值类型 函数名 (参数列表)
{
函数体语句
return表达式//返回整形 return 1 返回浮点型 return 3.14
}
实现一个加法函数 功能是 传入两个整形数据 计算数据相加的结果 并且返回
1.返回值类型 int
2.函数名 add
3.参数列表 (int num1,int num2)
4.函数体语句 int sum=num1+num2;
5.return表达式 return sum;
执行:
int add(int num1,int num2)
{
int sum=num1+num2;
return sum;
}
- 函数-函数的调用
使用定义好的函数
1.函数调用语法:函数名称(参数)
2.在函数定义的时候,num1和num2并没有真实数据,他只是一个形式上的参数,简称形参
3.底下代码a和b称为实际参数,简称实参
4.当调用函数时候,实参的值会传递给形参
main函数中调用add函数
#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=" << c << endl;
return 0;
}
- 函数-值传递
1.所谓值传递,就是函数调用时实参将数值传入形参
2.值传递时,如果形参发生,并不会影响实参
3.如果函数不需要返回值,声明的时候可以写void(可以写return;但后面return后面什么都不要写),或者直接不写。
void无类型
#include<iostream>
using namespace std;
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);
cout << "a=" << a << endl;//还是不改变
cout << "b=" << b<< endl;//还是不改变
return 0;
}
- 函数-函数的常见样式
1.常见的函数样式有4种
(1)无参无返
(2)有参无返
(3)无参有返
(4)有参有返
2.
(1)void是无类型,不用return
(2)int,float,与返回值return有关
(3)void如果已经规定为无参无返了,则不能在函数体语句里面用void a=10
3.
#include<iostream>
using namespace std;
void test01()
{
cout << "this is test01" << endl;
}
void test02(int a)
{
cout << "this is test02 a=" << a << endl;
}
int test03()
{
cout << "this is test03" << endl;
return 1000;
}
int test04(int b)
{
cout << "this is test04 b=" << b << endl;
return 100;
}
int main()
{
test01();
test02(100);
int num1 = test03();
cout << "num1=" << num1 << endl;
int num2 = test04(10000);
cout << "num2=" << num2 << endl;
}
输出结果:
int num*=test0*(int a);
最后num的值与return有关,而a只在cout里有用
- 函数-函数的声明
作用:告诉编译器函数名称及如何调用函数,函数的实际主体可以单独定义。
函数的声明可以多次,但是函数的定义只能有一次。
1.函数的声明
函数的声明:提前告诉编译器函数的存在,可以利用函数的声明。
如:int max(int a,int b)
函数的定义:
具体的函数体语句
如:
{
return a>b?a:b;
}
#include<iostream>
using namespace std;
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
int a = 10;
int b = 20;
int c = max(a, b);
cout << "c=" << c << endl;
}
输出结果:
- 函数-函数的分文件编写
作用:让代码结构更加清晰
1.函数分文件编写一般有4个步骤
(1)创建后缀名为.h的头文件
(2)创建后缀名为.cpp的源文件
(3)在头文件中写函数的声明
(4)在源文件中写函数的定义