C++中头文件的概念与基本编写方法

2020-01-06 14:12:30王冬梅

头文件里有些什么?
头文件的使用主要体现在两个方面,一个是重(音chóng)用(即多次使用),另一个是共用。

那些提供标准库函数的头文件就是为了重用。很多程序或工程可能会用到这些标准库函数,把它们写在头文件里面,每次使用的时候只需要包含已经完成的头文件就可以了。

头文件的共用主要体现在C++的多文件结构中。由于目前的程序规模较小,尚不需要用到多文件结构,所以在此对头文件的共用不作展开。有兴趣的读者可以查阅相关书籍。
那么,如果我们要自己编写一个可以重用的头文件,里面应该写些什么呢?

类似于标准库函数,我们在头文件里面应该模块化地给出一些函数或功能。另外还应该包括独立实现这些函数或功能的常量、变量和类型的声明。

下面我们就来看一个头文件应用的实例:


//shape.h
#include "math.h"//在计算三角形面积时要用到正弦函数
const double pi=3.14159265358;//常量定义
struct circle//类型声明
{
  double r;
};
struct square
{
  double a;
};
struct rectangle
{
  double a,b;
};
struct triangle
{
  double a,b,c,alpha,beta,gamma;
};
double perimeter_of_circle(double r)//函数定义
{
  return 2*pi*r;
}
double area_of_circle(double r)
{
  return pi*r*r;
}
double perimeter_of_square(double a)
{
  return 4*a;
}
double area_of_square(double a)
{
  return a*a;
}
double perimeter_of_rectangle(double a,double b)
{
  return 2*(a+b);
}
double area_of_rectangle(double a,double b)
{
  return a*b;
}
double perimeter_of_triangle(double a,double b,double c)
{
  return a+b+c;
}
double area_of_triangle(double a,double b,double gamma)
{
  return sin(gamma/180*pi)*a*b/2;
}
//main.cpp
#include "iostream.h"
#include "shape.h"//包含我们编写好的shape.h
int main()
{
  circle c={2};
  square s={1};
  rectangle r={2,3};
  triangle t={3,4,5,36.86989,53.13011,90};
  cout <<"Perimeter of circle " <<perimeter_of_circle(c.r) <<endl;
  cout <<"Area of square " <<area_of_square(s.a) <<endl;
  cout <<"Perimeter of rectangle " <<perimeter_of_rectangle(r.a,r.b) <<endl;
  cout <<"Area of triangle " <<area_of_triangle(t.b,t.c,t.alpha) <<endl;
  return 0;
}

运行结果:


Perimeter of circle 12.5664
Area of square 1
Perimeter of rectangle 10
Area of triangle 6

我们编写好了shape.h头文件,以后用到计算图形周长或面积的时候,就不需要重新编写函数了,只需要包含这个头文件就行了。