• 作用:让代码结构更加清晰
  • 函数份文件编写一般有4个步骤
  1. 创建后缀名为.h的头文件
  2. 创建后缀名为.cpp的源文件
  3. 在头文件中写函数的声明
  4. 在源文件中写函数的定义 ```cpp

// main.cpp // Created by zhoukai on 2022/1/10. //

include

include “swap.h”

using namespace std; // 函数定义 void swap(int a, int b) { int temp = a; a = b; b = temp; cout << a << endl; cout << b << endl; }

  1. ```cpp
  2. // swap.h
  3. //
  4. // Created by zhoukai on 2022/1/10.
  5. //
  6. #ifndef DEMO02_SWAP_H
  7. #define DEMO02_SWAP_H
  8. // 函数声明
  9. void swap(int a, int b);
  10. #endif //DEMO02_SWAP_H
  1. // swap.cpp
  2. //
  3. // Created by zhoukai on 2022/1/10.
  4. //
  5. #include <iostream>
  6. #include "swap.h"
  7. using namespace std;
  8. // 函数定义
  9. void swap(int a, int b) {
  10. int temp = a;
  11. a = b;
  12. b = temp;
  13. cout << a << endl;
  14. cout << b << endl;
  15. }