返回列表 發帖

const作用域範圍

在全局作用域裏定義非 const 變量時,它在整個程序中都可以訪問。我們可以把壹個非 const 變更定義在壹個文件中,假設已經做了合適的聲明,就可在另外的文件中使用這個變量:
  // file_1.cc
  int counter;  // definition
  // file_2.cc
  extern int counter; // uses counter from file_1
  ++counter;          // increments counter defined in file_1
  與其他變量不同,除非特別說明,在全局作用域聲明的 const 變量是定義該對象的文件的局部變量。此變量只存在於那個文件中,不能被其他文件訪問。
  通過指定 const 變更為 extern,就可以在整個程序中訪問 const 對象:
  // file_1.cc
  // defines and initializes a const that is accessible to other files
  extern const int bufSize = fcn();
  // file_2.cc
  extern const int bufSize; // uses bufSize from file_1
  // uses bufSize defined in file_1
  for (int index = 0; index != bufSize; ++index)
  // ...本程序中,file_1.cc 通過函數 fcn 的返回值來定義和初始化 bufSize。而 bufSize 定義為 extern,也就意味著 bufSize 可以在其他的
  文件中使用。file_2.cc 中 extern 的聲明同樣是 extern;這種情況下,extern 標誌著 bufSize 是壹個聲明,所以沒有初始化式。

返回列表