- 函数的定义
返回值类型 函数名 (参数列表)
{
函数体语句
return表达式
}
- 函数的调用
#include <iostream>
using namespace std;
#include<ctime>//根据系统时间来取随机数的头文件
int add(int num1, int num2)//形参
{
int sum = num1 + num2;
return sum;
}
int main()
{
int a = 100;
int b = 520;
int c= add(a, b);//a和b称为实际的参数
cout << c << endl;
system("pause");
return 0;
}
- 值传递
#include <iostream>
using namespace std;
#include<ctime>//根据系统时间来取随机数的头文件
//值传递
//定义函数,实现两个数进行交换函数
//如果函数不需要返回值,声明的时候可以写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;
//返回值不需要时可以不写return
}
int main()
{
int a = 100;
int b = 500;
swap(a, b);
cout << "a=" << a << endl;//当我们做值传递的时候,函数的形参发生改变,并不会影响实参;
cout << "b=" << b << endl;
system("pause");
return 0;
}
- 函数的常见样式
无参无返
void test1()
{
cout<<"this is test01"<<endl;//形式参数的定义
}
int main()
{
test1();//形式参数的调用
}
无参有返
int test03()//无参有反
{
cout<<"this is test03"<<endl;
return 100;
}
int main()
{
int num1=test03()//利用一个参数接收返回值
cout<<"num1="<<num1<<endl;//所以返回值应该等于100
return 0;
}
有参无返
void test2(int a)
{
cout<<"this is test02 a="<<a<<endl;//形式参数的定义
}
int main()
{
test2(100);//形式参数的调用
}
有参有返
即上面函数调用的例子。
- 函数的声明
提前告知编译器函数的存在,可以利用函数的声明。声明可以写多次,但是定义只能写一次。格式如下:
int max(int a ,int b);
int max(int a ,int b)
{
return a>b?a:b;
}
- 函数的分文件编写
1.创建.h后缀名的头文件
2.创建.cpp后缀名的源文件
3.在头文件中写函数的声明
4.在源文件中写函数的定义