2009年7月21日 星期二

Static 的作用 (c++)

Static 主要有三種功能:

1. 修飾檔案中的全域變數或函式 保護檔案中的全域變數或函式只限於該檔案使用,不受其他檔案存取

2. 修飾函式中的區域變數,使區域變數具有全域變數的效果,受到static 修飾的變數只會初始一次.

例:
#include
using namespace std;

void func(void){
static int i=0;
i++;
printf("%d", i);
}
int main(void){
for(int j=0; j<10; j++)
func();

return 0;
}

印出:12345678910

3. 修飾類別中的資料或函式成員
static 成員可以用 類別名稱:: 直接使用

參考資料: http://shukaiyang.myweb.hinet.net/courses/cpp/static.zhtw.htm

沒有留言:

張貼留言