3-2 头文件

这篇博客详细介绍了C++中头文件的作用,包括类的声明、头文件的结构和作用、接口的概念以及#include指令的用法。强调了头文件作为代码使用者和编写者之间的合同,应当包含声明而非定义。并提供了标准头文件的防止重复包含保护结构以及头文件的最佳实践,如每个头文件只声明一个类,并与对应的源文件保持相同的文件名前缀。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Declaration of a class

In C++, seperated .h and .cpp files are used to define one class. 

Class declaration and prototypes in that class are in the header file(.h). 

All the bodies of these functions are in the sourse file(.cpp). 


The header files

If a function is declared in a header file, you must include the header file everywhere the function is used and where the function is defined. 

If a class is declared in a header file, you must include the header file everywhere the class is used and where class member functions are defined.  


Header=interface

The header is a contract between you and the user of your code. 

The compile enforces the contract by requiring you to declare all structures and functions before they are used. 


Structure of C++ program

declarations(.h)+definitions(.cpp)→ after pre-compiler


Declarations vs. Definitions

A .cpp file is a compile unit. 

Only declarations are allowed to be in .h

        extern viriables

        function prototypes

        class/struct declaration(class/struct is declaration ONLY!!!)


#include

#include is to insert the included file into the file(couls be .cpp or .h)at where the #include statement is. 

        - #include"xx.h": first search in the current direction, then the directories declared somewhere.

        - #include<xx.h>: search in the specified directories

        - #include<xx>: same as #include<xx.h>


Standard header file structure

#ifndefine HEADER_FLAG

#define HEADER_FLAG

//type declaration here

#end if//HEADER_FLAG


Tips for header

1.Only one class declaration per header file.

2.Associated with one source file in the same prefix of file name.

3.The contents of a header file is surrounded with #ifndef #define #endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值