前言
在同一个文件下进行编程时,我们时常会因为项目的规模过大而很难准确的定位我们编写的函数、很难找到我们的错误,而分文件编写则能够有效的避免这些问题。
一、分文件编写的步骤
- 创建后缀名为 .h 的头文件,创建后缀名为 .cpp 的源文件,二者前缀名尽量一致
- 在头文件中写函数的声明、结构体的声明、类的声明
- 在源文件中写函数的定义、类中成员函数的定义
二、标准写法(以Swap.h为例)
头文件
//条件编译(避免运行时重复编译,降低效率)
//#pragma once现在已经支持大部分编译器
#pragma once
//#ifndef #define #endif是传统的写法
#ifndef _SWAP_H
#define _SWAP_H
//头文件的引入
//此处包含此头文件后,在swap.cpp文件中不需要再包含
#include <iostream>
using namespace std;
//函数的声明、结构体的声明、类的声明
#endlf
源文件
//引入自己编写的头文件
#include "Swap.h"
//函数的定义、类的成员函数的定义
三、样例(以Person类为例)
Person.h文件
#pragma once
#ifndef _PERSON_H
#define _PERSON_H
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
//函数的声明
Person();
~Person();
void ShowInfo();
private:
string name;
int age;
}
#endif
Person.cpp文件
//包含头文件
#include "Person.h"
//函数的实现
Person::Person()
{
}
Person::~Person()
{
}
void Person::ShowInfo()
{
cout << "姓名:" << name << " 年龄:" << age << endl;
}
main函数文件
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
Person p1;
p1.ShowInfo();
system("pause");
return 0;
}
总结
- 分文件编写的意义:可以让代码结构更清晰、方便多人协作