1.创建.h后缀名的头文件

swap.h头文件

  1. #include <iostream>
  2. using namespace std;
  3. // 函数声明
  4. void swap(int a, int b);

2.创建.cpp后缀名的源文件

swap.cpp文件

  1. // 引入自定义头文件
  2. #include "swap.h"
  3. void swap(int a, int b) {
  4. int temp = a;
  5. a = b;
  6. b = temp;
  7. cout << "a = " << a << endl;
  8. cout << "b = " << b << endl;
  9. }

3.在头文件中写函数的声明

4.在源文件中写函数的定义

5.在要使用该函数的文件中引入头文件

  1. #include <iostream>
  2. #include "swap.h"
  3. using namespace std;
  4. int main(void) {
  5. int a = 10;
  6. int b = 20;
  7. swap(a, b);
  8. // 指针所占内存空间
  9. // 在32位操作系统下,指针是占4个字节空间大小,不管是什么数据类型
  10. // 在64位操作系统下,指针是占用8个字节的空间大小
  11. /*cout << sizeof(char*) << endl;*/
  12. system("pasue");
  13. return 0;
  14. }