const物件僅在檔案內有效
阿新 • • 發佈:2018-12-02
當以編譯時初始化的方式定義一個const物件時,編譯器將在編譯的過程中把用到該變數的地方都替換成對應的值。為了執行替換,編譯器必須知道變數的初始值。如果程式包含多個檔案,則每個用了const物件的檔案都必須得能訪問到它的初始值才行。要做到這一點,就必須在每一個用到變數的檔案中都有對它的定義。為了支援這一用法,同時避免對同一變數的重複定義,預設情況下,const物件被設定為僅在檔案內有效。當多個檔案中出現了同名的const變數時,其實等同於在不同檔案中分別定義了獨立的變數。
例子:
1 // file_1.h 2 #ifndef FILE_1 3 #define FILE_1 4void f(); 5 #endif
1 // func.cpp 2 #include <file_1.h> 3 #include <iostream> 4 5 const int x = 998; 6 void f() 7 { 8 std::cout << "func:&x " << &x << std::endl; 9 }
1 // main.cpp 2 #include <iostream> 3 #include <string> 4#include <file_1.h> 5 6 const int x = 998; 7 int main() 8 { 9 f(); 10 std::cout << "main:&x: "<<&x << std::endl; 11 return 0; 12 }
輸出:
x的地址完全不一樣,說明2個x變數時獨立的,不是同一個。
如果想要在不同的檔案間共享同一個const變數怎麼辦,方法是對於const變數不管是宣告還是定義都新增extern關鍵字,這樣只需定義一次就好了。
例子:
1 // file_1.h 2 #ifndef FILE_1 3 #define FILE_1 4 extern const int x; 5 void f(); 6 #endif
1 // func.cpp 2 #include <file_1.h> 3 #include <iostream> 4 5 extern const int x = 998; 6 void f() 7 { 8 std::cout << "func:&x " << &x << std::endl; 9 }
1 // main.cpp 2 #include <iostream> 3 #include <string> 4 #include <file_1.h> 5 6 extern const int x; 7 int main() 8 { 9 f(); 10 std::cout << "main:&x: "<<&x << std::endl; 11 return 0; 12 }
輸出:
地址一樣,說明是同一個變數