程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 靜態成員變量與靜態成員函數

靜態成員變量與靜態成員函數

編輯:C++入門知識

靜態成員變量不專屬於某個對象,他屬於整個類中所有對象的成員變量,在實例化一個對象的時候可能無法給它開辟內存,因此我們需要在全局為他開辟內存。


[cpp] 
#include<iostream> 
using namespace std; 
class A   
{   
public:   
<span style="white-space:pre">  </span>static int count; 
<span style="white-space:pre">  </span>A(int i):key(i) 
<span style="white-space:pre">  </span>{ 
<span style="white-space:pre">      </span>count++; 
<span style="white-space:pre">      </span>cout<<"構造函數!"<<endl; 
<span style="white-space:pre">  </span>} 
<span style="white-space:pre">  </span>~A() 
<span style="white-space:pre">  </span>{ 
<span style="white-space:pre">      </span>count--; 
<span style="white-space:pre">      </span>cout<<"析構函數!"<<count<<endl; 
<span style="white-space:pre">  </span>} 
<span style="white-space:pre">  </span>int Getkey() 
<span style="white-space:pre">  </span>{ 
<span style="white-space:pre">      </span>return key; 
<span style="white-space:pre">  </span>} 
<span style="white-space:pre">  </span>int GetCount() 
<span style="white-space:pre">  </span>{ 
<span style="white-space:pre">      </span>return count; 
<span style="white-space:pre">  </span>} 
private: 
<span style="white-space:pre">  </span>int key; 
};   
int A::count=0; 
int main() 
{ www.2cto.com
<span style="white-space:pre">  </span> A a(5); 
<span style="white-space:pre">  </span> cout<<a.Getkey()<<" "<<a.GetCount()<<endl; 
<span style="white-space:pre">  </span> A b(6); 
<span style="white-space:pre">  </span> //可以直接用類名去訪問靜態成員變量 
<span style="white-space:pre">  </span> cout<<A::count<<endl; 
<span style="white-space:pre">  </span> cout<<b.GetCount()<<endl; 
<span style="white-space:pre">  </span> return 0; 

靜態成員函數不能訪問普通成員變量以及普通成員函數,但是可以訪問靜態成員變量和靜態成員函數。因為靜態成員函數是屬於整個類的,所以他不能訪問某個對象的 成員
變量,因為它沒有this指針,但是他可以訪問靜態成員函數和靜態成員變量。
[cpp] 
#include<iostream> 
using namespace std; 
class A   
{   
public:   
     
    A(int i):key(i) 
    { 
        count++; 
        cout<<"構造函數!"<<endl; 
    } 
    ~A() 
    { 
        count--; 
        cout<<"析構函數!"<<count<<endl; 
    } 
    int Getkey() 
    { 
        return key; 
    } 
     static int GetCount() 
    { 
        return count; 
    } 
    static void Show() 
    { 
        cout<<count<<endl; 
        count++; 
        //需要講GetCount變成static才能被Show訪問 
        cout<<GetCount(); 
    } 
private: 
    int key; 
    static int count; 
};   
int A::count=10; 
int main() 

    A::Show(); 
     A a(5); 
     cout<<a.Getkey()<<" "<<a.GetCount()<<endl; 
     A b(6); 
 
     cout<<b.GetCount()<<endl; 
     return 0; 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved