c++ 头文件

时间:2022-04-25
本文章向大家介绍c++ 头文件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

可以将程序分为二部分:

头文件:包含结构声明和使用这些结构的函数的原型

源代码文件: 包含与结构有关的函数的代码

不要将函数的定义或变量的声明放在头文件里,

一般头文件可以包含以下内容

>函数原型

>使用#define或const定义的符号常量

>结构声明

>类声明

>模板声明

>内联函数

在包含头文件时我们使用 #include "head.h"而不是#include <head.h>

如果使用<>  c++编译器将在存储标准头文件的主机系统的文件系统中查找;

如果使用""   编译器会首先查找当前的工作目录或源代码目录,如果没有找到头文件,再去标准位置查找

注意:在IDE中,不要将头文件加入到项目列表中,也不要在源代码文件中使用#include 来包含其它源代码文件

#ifndef COORDIN_H
#define COORDIN_H

struct polar
{
    double distance;  //distance from origin
    double angle;      //direction form origin
};

struct rect
{
    double x;    //horizontal distance form origin
    double y;    //vertical distance from origin
};

polar rect_to_polar(rect xypos);
void show_polar(polar dapos);

#endif

在同一个文件中只能将一个头文件包含一次,但有可能会因为错误操作包含多次,有一种标准的c/c++技术可以避免

多次包含一个头文件。它是基于预处理编译指令#ifndef(if not defined)的。上边的代码意味着仅当以前没有

使用预处理编译器指令#define定义名称COORDIN_H时,才处理#ifndef和#endif之间的语句

源代码文件

#include<iostream>
#include<cmath>
#include "coordin.h"

using namespace std;

polar rect_to_polar(rect xypos)
{
    polar answer;
    answer.distance=sqrt(xypos.x*xypos.x+xypos.y*xypos.y);
    answer.angle=atan2(xypos.y,xypos.x);
    return answer;
}
void show_polar(polar dapos)
{
    cout<<dapos.angle<<"   "<<dapos.distance<<endl;
}

调用

#include<iostream>
#include "coordin.h"
using namespace std;
int main()
{
    rect replace;
    polar pplace;
    cout<<"Enter the x and y values:n";
    while(cin>>replace.x>>replace.y)
    {
        pplace=rect_to_polar(replace);
        show_polar(pplace);
    }    
    cin.get();
}