1. 定义
#include<iostream>
using namespace std;
/*返回值类型 函数名(参数列表)
{
函数体语句
return表达式
}
*/
int Add(int num1,int num2){
int sum = num1+num2;
return sum;
}
int main(){
int num1 =0;
int num2 =0;
cout << "请输入num1:" << endl;
cin>>num1;
cout << "请输入num2:" << endl;
cin>>num2;
int c = Add(num1,num2);
cout << "num1与sum2之和为:"<< c <<endl;
system("pause");
return 0;
}
2.常见样式
#include<iostream>
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, ";
int a =10;
return a;
}
//4.有参有返
int test04(int a){
cout << "this is test04, ";
return a;
}
int main(){
test01();
test02(5);
int num1=test03();
cout << num1 <<endl;
int num2 =test04(1000);
cout << num2 <<endl;
system("pause");
return 0 ;
}
3. 声明
#include<iostream>
using namespace std;
//函数的声明:提前告知主函数要调用的函数,即为声明
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)
{
return a>b?a:b;
}
4. 值传递
#include<iostream>
using namespace std;
//值传递时,形参发生任何改变都不会影响实参
//实现两个数字进行交换函数
void swap(int num1,int num2){
cout << num1<<" "<< num2 <<endl;
int temp = num1;
num1 = num2;
num2 = temp;
cout << num1<<" "<< num2 <<endl;
}
int main(){
int num1 =0;
int num2 =0;
cout << "请输入num1:" << endl;
cin>>num1;
cout << "请输入num2:" << endl;
cin>>num2;
swap(num1,num2);
system("pause");
return 0;
}
5. 分文件编写
步骤:
(1)创建xxx.h文件,进行函数声明
(2)创建xxx.cpp文件,进行函数定义
(3)main文件,加上#include “xxx.h”