一、分文件编写
作用:让代码结构更加清晰
步骤:
1)创建后缀名为.h的头文件
2)创建后缀名为.cpp的源文件
3)在头文件中写函数的声明
4)在源文件中写函数的定义
示例:
1、建立一个c++文件,取名为Chapeter04.cpp
#include <iostream>
using namespace std;
#include "swap.h"
int main()
{
int a = 10;
int b = 20;
swap(a, b);
}
2、创建一个名为swap.h的头文件
#include <iostream>
using namespace std;
//函数的声明
void swap(int a, int b);
3、创建一个名为swap.cpp的C++文件
#include "swap.h"
//函数的定义
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
输出结果:
a=20
b=10