学习:函数的分文件编写

目的:使代码结构更加清晰

函数分文件编写一般有4个步骤:

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

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

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

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


例子:我们需要定义一个名为swap的函数,该函数具有交换数值的功能

1、定义个swap.h的头文件,并且进行申明

#include<iostream>
using namespace std;

//头文件只需要申明函数
void swap(int a, int b);

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

//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;
}

main主文件

#include<iostream>
#include<string>
#include "swap.h"
// 直接调用std空间使用
using namespace std;



//分文件编写使代码结构更加清晰
int main() {
	swap(1, 2);
	system("pause");
	return 0;
}

原文地址:https://www.cnblogs.com/zpchcbd/p/11840607.html