函数分文件编写一般有4步。
1.创建后缀名为.h的头文件。
2.创建后缀名为.cpp的源文件。
3.在头文件中写函数的声明。
4.在源文件中写函数的定义。
swap.h 文件:
#include<iostream>
using namespace std;
// 函数声明
int swap(int a,int b);
swap.cpp 文件:
#include "swap.h"
// 函数定义
int swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
testswap.cpp 文件:
#include "swap.h"
int main()
{
swap(49, 29);
return 0;
}
本文介绍了一种函数分文件编写的四步法,并通过一个具体的swap函数交换实例进行演示。包括创建头文件和源文件,以及如何在不同文件中声明和定义函数。
488

被折叠的 条评论
为什么被折叠?



