- 註冊時間
- 2006-10-8
- 最後登錄
- 2019-6-20
- 主題
- 查看
- 積分
- 1306
- 閱讀權限
- 110
- 文章
- 1392
- 相冊
- 0
- 日誌
- 1
   
狀態︰
離線
|
區域變數的定義加上 static,其使用範圍與沒有加上 static 是沒有區別的,但是其生命期就 如同 全域變數一樣,以下例來解說:
例 6.
int square(int i)
{ static int count=0;
count++;
return i*i;
}
說明:
函數 square 中含一 static 區域變數 count。
變數 count 於編譯後就存在了。
變數 count 不管函數 square 呼叫 多少次, 僅 initialize 一次。每呼叫函數 square 一次, 變數 count 就增加 1。
count 可以說是 專屬於 函數 square 的全域變數。
全域變數 的定義加上 static,則 該變數 就 變成 專屬於 該檔案 的 全域變數,其它檔案 就 無法 引用該 變數, 即 其它檔案 就不能 含有 該變數的 extern 指令。
例 7. 設有三個檔案 file.h、 file.c 及 main.c 其內容分別如下:
檔案 file.h 含
void Add(int n);
void Mult(int n);
int get();
檔案 file.c 含
#include "file.h"
static int s=0;
void Add(int n) {s=s+n;}
void Mult(int n) {s=s*n;}
int get(){return s;}
檔案 main.c 含
#include < stdio.h >
#include "file.h"
void main()
{Add(5);
Mult(10);
printf("s=%d\n",get());
}
說明:
檔案 file.c 含一 static 全域變數 s,該 變數 僅能於 file.c 引用。
檔案 main.c 不可加上 extern int s; 而引用變數 s。
程式執行的結果為
s=50
C++ 程式 class 的設計方式 非常類似 file.c 與 file.h 的架構,變數 s 就如同一個 private 的 data member。
一個函數的定義加上 static, 該 函數 也就變成 專屬該檔案 的函數,其它檔案 就無法 呼叫該函數,於 C++ class 的設計,就好像一個 private 的 member function。
|
|