【翁恺】04-头文件

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 those functions are in the source file(.cpp)

(.h)--declaration---声明

(.cpp)--definition--定义

c++中严格区分声明和定义

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

1541468968452

#include 编译预处理指令, 把头文件里面内容插入过来。

g++ a.cpp b.cpp --save-temps  // 保存中间文件

.ii  编译预处理指令结束后结果  .s  汇编代码  .o 目标代码  .out  可执行程序

.h 不能放变量的定义       使用extern 声明一个变量

C++ 编译器会把所有名字前会加入下划线。比如  _global。

编译完成得到 .o 文件。

.cpp (编译预处理).ii     (编译器) .s  (汇编器) .o   ld 链接器 .out

编译时候是针对单个 cpp 的,所以编译没问题,ld 出现了问题。

需要在某个地方对声明的变量进行定义。否则,ld 就会找不到该变量。

g++ a.cpp b.cpp --save-temps  -Wall // Wall 输出所有警告, 要消灭所有警告。

declarations vs. definitions

  • a .cpp file is a compile unit(编译单元)
  • only declarations are allowed to be in .h
    • extern variables  // extern 的
    • function prototypes // 原型  没有 {}
    • class/struct declaration // 没有类的定义,只有类的声明

c++一次只对一个.cpp文件进行编译,链接的时候可能会出现重复定义的变量而出错

class/struct只有声明没有定义

#inlcude

  • "# include" is to insert the included file into the .cpp file 或 .h  at where the "#include" statement is
    • "#include xx.h" :first search in the current directory(当前目录),then the directories declared somewhere
    • "#include <xx.h>":search in the specified directories(系统目录)
    • "#include ":same as "#include <xx.h>"

iostream.h----->istream

standard header file structure

#ifndef HEADER_FLAG
#define HEADER_FLAG
//type declaration here
#endif //HEADER_FLAG

标准头文件结构,防止声明重复出现, 如果有了声明的东西,这些内容就不会进入编译器

.h 内放 声明 而不放 定义, 是为了避免 多个 .cpp  include 同一个 .h 时候, ld 遇到了重复定义的东西。

标准头文件结构,是防止一个 .cpp 里面 include 同一个 .h 多次,出现那个 .h 里面 类的声明重复出现。

tips for header

  1. 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"

为什么不能 include  .cpp ?因为.cpp 内都是 body,  都是定义, 如果被 include 多次,那么都是重复的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理心炼丹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值