c++ 前置声明

前置声明(forward declaration) 

维基百科上的定义是:

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, or a function) for which the programmer has not yet given a complete definition. It is required for a compiler to know the type of an identifier (size for memory allocation, type for type checking, such as signature of functions), but not a particular value it holds (in case of variables) or definition (in the case of functions), and is useful for one-pass compilers. Forward declaration is used in languages that require declaration before use; it is necessary for mutual recursion in such languages, as it is impossible to define these functions without a forward reference in one definition. It is also useful to allow flexible code organization, for example if one wishes to place the main body at the top, and called functions below it. 

我们可以从上面定义中提取出如下信息:
(1)前置声明是针对类型,变量或者函数而言的
(2)前置声明是个不完整的类型

(3)前置声明会加快程序的编译时间

前置声明有哪些作用

(1)前置声明可以有效的避免头文件循环包含的问题,看下面的例子

  1. // circle.h  
  2. #include "point.h"  
  3.   
  4. struct circle {  
  5.     struct coordinate center;  
  6. };   
  1. // point.h  
  2. #include "circle.h"  
  3.   
  4. struct coordinate {  
  5.     struct circle cir;  
  6. };  
  1. #include "circle.h"  
  2.   
  3. int main(int argc, const char *argv[])  
  4. {  
  5.     struct circle cir;  
  6.     return 0;  
  7. }  

如果编译这个程序,你会发现因为头文件循环包含而发生编译错误,即使修改头文件如下也还是不行:

  1. #ifndef __CIRCLE_H__  
  2. #define __CIRCLE_H__  
  3. // circle.h  
  4. #include "point.h"  
  5.   
  6. struct circle {  
  7.     struct coordinate center;  
  8. };  
  9. #endif  
  1. #ifndef __POINT_H__  
  2. #define __POINT_H__  
  3. // point.h  
  4. #include "circle.h"  
  5.   
  6. struct coordinate {  
  7.     struct circle cir;  
  8. };  
  9. #endif  

这个时候就可以使用前置声明轻松的解决这个问题,但是必须要使用指向不完整类型的指针了。

  1. #ifndef __CIRCLE_H__  
  2. #define __CIRCLE_H__  
  3. // circle.h  
  4. //#include "point.h"  
  5.   
  6. struct coordinate;  
  7. struct circle {  
  8.     struct coordinate *center;  
  9. };  
  10. #endif  
  1. #ifndef __POINT_H__  
  2. #define __POINT_H__  
  3. // point.h  
  4. //#include "circle.h"  
  5.   
  6. struct circle;  
  7. struct coordinate {  
  8.     struct circle *cir;  
  9. };  
  10. #endif  

可以发现我们连头文件都不用包含的,这就可以缩短编译的时间了。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章