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  

可以發現我們連頭文件都不用包含的,這就可以縮短編譯的時間了。


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