c++头文件

本文介绍了C++中头文件的使用,包括类的定义、头文件中声明与定义的区别以及头文件的最佳实践。类的声明和函数原型通常在.h文件中,而函数的实现则在.cpp文件。头文件仅允许包含声明,如extern、函数原型和类/结构声明。建议每个头文件对应一个类,并与相应的源文件名字前缀一致。

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

C++程序设计(c++头文件)

Definition of a class
  • In C++,separated .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 function are in the source file(.cpp).

    include叫做编译预处理

示例1

a.h的代码

#ifndef A //如果没有定义宏,则定义这个宏
#define A
using namespace std;
void show(){
    cout<<"hello world"<<endl;
}
#endif // A

main.cpp的代码

 #include<iostream>
 #include"a.h"
 using namespace std;
 int main(){
     show();
 }

结果

hello world
Declarations vs. Definition
  • A.cpp file is a compile unit
  • only declarations are allowed to be in .h
    1.extern
    2.functionprototypes
    3.class/struct declaration
Tips for header

1.One class declaration per header file
2.Associated with one source file in the same prefix of 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、付费专栏及课程。

余额充值