關於extern const

首先,有一點需要明確,就是const對象默認爲文件的局部變量。通常,在全局作用域定義的非const變量,它在整個程序中都可以訪問,例如

//file1.cpp
int counter;

//file2.cpp
extern int counter;
cout << counter <<endl;

在file1.cpp中定義全局變量counter, 在file2.cpp中可以訪問;

但是,對於const全局變量,這樣做就會錯誤,例如

//file1.cpp
const int counter = 0;

//file2.cpp
extern const int counter;
count << counter <<endl;
這個例子,在鏈接時會報找不到conuter的錯誤。原因是因爲const對象是文件的局部變量,也就是說counter僅在file1.cpp可見。


通過指定const變量爲extern, 就可以在整個程序中訪問const 對象,如

//file1.cpp
extern const int counter = 0;

//file2.cpp
extern const int counter;
<pre name="code" class="cpp">count << counter <<endl<span style="font-family: Arial, Helvetica, sans-serif;">;</span>







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