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
#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
- one class declaration per header file 一个头文件里面只放一个类的声明
- associated with one source file in the same prefix of file name (源代码用相同前缀)
- the contents of a header file is surrounded with "#ifndef #define #endif"
为什么不能 include .cpp ?因为.cpp 内都是 body, 都是定义, 如果被 include 多次,那么都是重复的。