C/C++靜態類和this指針詳解
1、靜態類
C++的靜態成員不僅可以通過對象來訪問,還可以直接通過類名來訪問。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class CBook{ public : static double price; //需要通過類外來進行初始化 } int main( void ){ CBook book; book.price; //通過對象來訪問 CBook::price //通過類名來訪問 return 0; } |
靜態成員變量
對應靜態成員有以下幾點需要注意:
(1)靜態數據成員可以是當前類的類型,而其他數據成員只能是當前類的指針或應用類型。
1
2
3
4
5
6
7
|
class CBook{ public : static double price; CBook book; //非法定義,不允許在該類中定義所屬類的對象 static CBook m_book; //正確 CBook *book; //正確 }; |
(2)靜態數據成員可以作為其他成員函數的默認參數(不同的數據類型不能作為參數)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class CBook{ public : int pages; static double price; //定義一個函數,以靜態數據作為默認參數 void outPutInfo( int data = price){ //實現 } //錯誤定義,普通數據不能作為默認參數 void outPutPage( int data = pages){ //實現 } }; |
靜態函數
1
|
static void outPut(); |
(1)類的靜態成員函數只能訪問靜態數據成員,不能訪問普通數據成員(因為沒有this指針)。
(2)靜態成員函數不能定義為const成員函數(即靜態成員函數末尾不能加上const關鍵字)
1
|
static void outPut() const ; //錯誤定義 |
(3)在定義靜態成員函數時,如果函數的實現位于類體外,則在函數的實現部分不能再標識static關鍵字。
1
2
3
4
|
//錯誤的定義 static void CBook::outPutInfo(){ //實現 } |
關于靜態類我們在總結一下:
(1)類的靜態成員函數是屬于整個類而非類的對象,所以它沒有this指針,這就導致 了它僅能訪問類的靜態數據和靜態成員函數。
(2)不能將靜態成員函數定義為虛函數。
2、this
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class CBook{ public : int pages; void outputPages(){ cout<<pages<<endl; } }; int main(){ CBook book1,book2; book1.pages = 10; book2.pages = 20; book1.outputPages(); book2.outputPages(); return 0; } |
book1和book2兩個對象都有自己的數據成員pages,在調用outputPages時均輸出自己的成員數據,那二者是如何區分的呢?答案是this指針。
在每個類的成員函數(非靜態成員函數)都隱含一個this指針,指向被調用對象的指針,其類型為當前類的指針類型。
所以類似于上面的outputPages()方法,編譯器將其解釋為:
1
2
3
4
5
6
7
|
//函數調用 book1.outputPages(&book1); //函數實現 void outputPages(CBook * this ){ //隱含的this指針 cout<< this ->pages<<endl; //使用this指針訪問數據成員 } |
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
/** * 本示例為了說明this的三種用法! */ package test; public class ThisTest { private int i= 0 ; ThisTest( int i){ //(1)this.i表示成員變量i,i表示參數 this .i=i+ 1 ; } ThisTest(String s){ System.out.println( "String constructor: " +s); } ThisTest( int i,String s){ //(2)this調用第二個構造器 this (s); this .i=i++; } public ThisTest increment(){ this .i++; //(3)返回的是當前的對象 return this ; } public static void main(String[] args){ ThisTest tt0= new ThisTest( 10 ); ThisTest tt1= new ThisTest( "ok" ); ThisTest tt2= new ThisTest( 20 , "ok again!" ); System.out.println(tt0.increment().increment().increment().i); } } |
這里說明一下,this表示當前對象的引用,另this不能用在static方法中,這也就是為什么在靜態函數無法調用成員變量的原因了。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!