在C語言中,static 具有的兩重意義:
(1) 如果 static int foo; 這一句位於函數中,則 static 表示的是儲存屬性,表明 foo 是一個靜態變數。放在靜態儲存區,只佔一份空間。它的生存周期和程式一樣長。
(2) 如果 static int foo; 這一句位於函數外面,則 foo 是一個全域變數,static 不再是表示儲存性質,而是作為限制符來使用:用來限制全域變數 foo 的可見範圍,將其範圍限制於所在的檔案內,在其它檔案中是不可見的。 static void func();表示該函數只在本檔案可見。
在C++中,類中的static成員表示所有對象共用儲存區。靜態成員函數只可以訪問靜態成員。靜態成員初始化必須放在檔案範圍,即使是私人成員。靜態成員函數調用可以用對象+成員函數,也可以用類+成員函數進行調用。
// Example of the static keywordstatic int i; // Variable accessible only from this filestatic void func(); // Function accessible only from this fileint max_so_far( int curr ){ static int biggest; // Variable whose value is retained // between each function call if( curr > biggest ) biggest = curr; return biggest;}// C++ onlyclass SavingsAccount{public: static void setInterest( float newValue ) // Member function { currentRate = newValue; } // that accesses // only static // membersprivate: char name[30]; float total; static float currentRate; // One copy of this member is // shared among all instances // of SavingsAccount};// Static data members must be initialized at file scope, even// if private.float SavingsAccount::currentRate = 0.00154;