C++ static / const /static const 型成員變量


C++static / const /static const 型成員變量


static關鍵字的兩類作用

C++中,static關鍵字的兩類作用分別是:

控制可見性與 控制存儲類型。


static成員變量的來源

staitc類型成員變量的出現是為了解決同一個類的所有對象共享參數的問題,實際上就是對存儲類型的控制。在C語言中,這樣的控制往往通過全局變量直線。而使用static成員變量的方法與使用global類型變量方法的相比有明顯的優點:

      1. 作用域,staticmember 是在class的作用域中的,它能夠防止命名的沖突。

      2. 數據封裝,staticmember可以是private類型的。

      3. 易於理解。


static成員變量的訪問

static類型成員變量的訪問可以直接通過作用域的符號實現。

在類的成員函數中可以不使用作用域的符號。


static成員變量的定義

與其它地方不同的是,類中的static僅僅起到變量聲明的作用。Static類型的成員變量必須在類外進行定義,而無法通過構造函數進行定義。static成員變量不在類體內定義,也不在構造函數內初始化(這樣就無法體現其共性)。


C++Primer》中這樣描述:

Unlikeordinary data members, static members are not initialized through theclass constructor(s) and instead should be initialized when they aredefined.

Thebest way to ensure that the object is defined exactly once is to putthe definition of static data members in the same file that containsthe definitions of the class noninline member functions.


Example1





Example2




Example3




Example4




static成員變量的進一步理解


C++Primer》中對staticdata member的描述是這樣的:

Astatic data member exists independently of any object of its class,each static data member is an object associated with the class, notwith the objects of that class.

也就是說,靜態成員是獨立於對象的,是與其所在類相關聯的。


普通的成員變量是對象的一部分,而static類型的變量獨立於任何的對象存在,它們不是對象的一部分。即staticmembers are not part of class objects


1.一個static型成員變量可以作為它自身類所在的成員變量。例如:





<C++Primer>是這樣解釋的:

Ordinarymembers are part of each object of the given class. Static membersexist independently of any object and are nor part of objects of theclass type. Because static data members are not part of any object,they can be used in ways that would be illegal for nonstatic datamembers.


  1. 一個static型的成員變量可以作為默認參數。而一個非static類型的成員變量例如:





<C++Primer>是這樣解釋的:

Anonstatic data member may not be used as a default argument becauseits value cannot be used independently of the object of which it is apart. Using a nonstatic data member as a default argument provides noobject from which to obtain the member's value and so is an error.

也就是說,使用非靜態數據成員做為默認參數是錯誤的,因為這時沒有一個具體的對象,無法從中得到成員的值。非靜態成員每一個object的對象可能都不一樣,而static針對每個class對象是一樣的。所謂默認參數在C++effective上說是編譯時綁定,說明在編譯的時候就確定了他得值,非靜態數據成員要到運行時候才能確定。

3.嵌套類可以含有靜態成員而局部類不能含有靜態成員。


const static類型成員變量

Example5




七例外的conststatic int類型

conststatic int 類型的成員變量可以在類中進行定義。


Example6




Example7



Example8




static修飾函數體內的變量

在函數中,被static修飾的對象只創建一次,連接方式為內部連接。在程序從main()中退出或者調用exit()時,系統自動調用該對象的析構函數(在析構函數中調用exit()可能陷入死循環)。如果用abort()退出程序,內存將不被釋放。標准C庫的atexit()可用於指定當程序跳出main()時應執行的操作。用atexit()注冊過的函數可以在所有對象的析構之前調用。

靜態對象的銷毀是按初始化的反序進行的。


static對可見性的控制

所有的全局對象都隱含為靜態存儲類。在文件范圍內(不在任何嵌套結構之中)定義

inta = 0; a被存儲在程序的靜態存儲區。

文件范圍內所有的名字都默認采用外部連接,也就是說,被外部文件可見。而在文件范圍內定義static int a = 0; a采用靜態存儲,內部連接。

一旦進入局部變量,static就不再改變變量的可見性,而只改變變量的存儲類型。

static用於修飾函數時,該函數只在當前文件可見。例如staticvoid function();



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM