1.值传递
所谓的值传递,就是函数调用时实参将数值传入给形参。值传递时,可如果形参发生并不会影响实参。
#include<iostream>
using namespace std;
#include<string>
//实现两个数字进行交换的函数
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;
}
void main() {
int a = 10;
int b = 20;
swap(a, b);
cout << "a=" <<a<< endl;
cout << "b=" << b << endl;
}
2.函数的声明
作用:告诉编译器函数名称及如何调用函数,函数的实际主体可以单独定义。
函数的声明可以多次,但是定义只能一次。
#include<iostream>
using namespace std;
#include<string>
int max(int a, int b);//函数声明
int max(int a, int b) {//函数定义
return a > b ? a: b;
}
void main() {
int a = 10;
int b = 20;
int c = max(a, b);//函数调用
cout<<c<<endl;
}
3.函数的分文件编写
作用:让代码结构更加清晰
函数分文件编写的步骤:
- 创建后缀名为.h的头文件
- 创建后缀名为.cpp的源文件
- 再头文件中写函数的声明
- 在源文件中写函数的定义
案例:实现两个数字交换的函数
swap.h头文件为:
#pragma once
#include<iostream>
using namespace std;
void swap(int a, int b);//函数的声明
swap.cpp源文件为:
#include<iostream>
#include"swap.h"
using namespace std;
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
test.cpp测试文件为:
#include<iostream>
#include"swap.h"
using namespace std;
void main() {
int a = 10;
int b = 20;
swap(a, b);
}