C/C++ 語言的Static

來源:互聯網
上載者:User
在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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.