作用:让函数结构更加清晰
1.创建后缀名为.h的头文件
2.创建后缀名为.cpp的头文件
3.在头文件中写函数的声明
4.在源文件中写函数的定义
未进行函数分文件编写的程序
#include <iostream>
using namespace std;
//#include "swap.h"
void swap(int a, int b);
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
int main()
{
int a = 10;
int b = 20;
swap(a, b);
system("pause");
return 0;
}
进行函数分文件编写的函数
swap.cpp源文件
#include "swap.h"
//
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
swap.h头文件
#pragma once
#include <iostream>
using namespace std;
void swap(int a, int b);
调用函数的源文件
#include <iostream>
using namespace std;
#include "swap.h"
int main()
{
int a = 10;
int b = 20;
swap(a, b);
system("pause");
return 0;
}