函数语法:
返回值类型 函数名 参数列表
{
函数体语句
return 表达式
}
例子:实现一个加法函数,传入两个整型数据,计算数据相加的结果,并且返回
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;
}
函数的调用语法:函数名(参数)
int main()
{
//main函数中调用add函数
int a = 10;
int b = 20;
//函数调用语法:函数名称(参数)
//a,b有实际值,称为实参
int c = add(a, b);
cout << "c=" << c << endl;
system("pause");//实现摁下摁键继续的功能
return 0;//返回正常退出值
}
函数的值传递!
值传递的时候,形参发生任何改变,不影响实参!
代码从main函数开始执行
#include<iostream>
#include<string>
using namespace std;
//值传递
//函数定义,实现两个数字进行交换函数
//如果函数不需要返回值,声明的时候可以写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;返回值不需要时,可以不写return
}
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;//返回正常退出值
}
函数的常见样式:
1.无参无返 2.有参无返 3.无参有返 4.有参有返
#include<iostream>
#include<string>
using namespace std;
//函数常见样式
//1.无参无返
void test01()
{
cout << "this is test01" << endl;
}
//2.有参无返
void test02(int a)
{
cout << "this is test02 a=" << a << endl;
}
//3.无参有返
int test03()
{
cout << "this is test03" << endl;
return 1000;
}
//4.有参有返
int test04(int a)
{
cout << "this is test04 a=" << a << endl;
return a;
}
int main()
{
//无参无返函数调用
test01();
//有参无返函数调用
test02(100);
//无参有返函数调用
int num1=test03();
cout << "num1=" << num1 << endl;
//有参有返函数调用
int num2 = test04(10000);
cout << "num2=" << num2 << endl;
system("pause");//实现摁下摁键继续的功能
return 0;//返回正常退出值
}
函数的声明
作用:告诉编译器函数名称及如何调用函数。函数的实际主体可以单独定义。
函数的声明可以多次,但是函数的定义只能用一次。
#include<iostream>
#include<string>
using namespace std;
//函数的声明
//比较函数,实现两个整型数字进行比较,返回较大的值
//提前告诉编译器函数的存在,可以利用函数的声明
// 函数的声明。函数的声明可以写多次,函数定义只能有一次
// 如果定义在main函数之前,可以不写声明;如果定义在main函数之后,必须要在前面函数声明;
//
int max (int a,int b)
//定义
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
int a = 10;
int b = 20;
cout << max(a, b) << endl;
system("pause");//实现摁下摁键继续的功能
return 0;//返回正常退出值
}
函数的分文件编写
作用:让代码结构更加清晰
函数分文件编写一般有4个步骤
1.创建后缀名为.h的头文件
解决方案资源管理器中头文件里新建项目,命名后缀为.h的文件。头文件里写函数的声明,前面的#include<iostream> using namespace std 要带上。
2.创建后缀名为.cpp的源文件
源文件新建项目,命名为.cpp的文件。
3.在头文件中写函数的声明
#include<iostream>
using namespace std;
//函数的声明
void swap(int a, int b);
4.在源文件中写函数的定义
#include"swap.h"
//"swap.h"带上双引号,表示我们自己编写的内容
//实现两个数字进行交换的函数
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
5.main函数前的头文件要带上swap.h
#include<iostream>
#include<string>
#include"swap.h"
using namespace std;
//函数的分文件编写
int main()
{
int a = 10;
int b = 20;
swap(a, b);
system("pause");//实现摁下摁键继续的功能
return 0;//返回正常退出值
}