static修飾類中成員,表示類的共享數據
1.static類成員
C++primer裏面說過,static類成員不像普通的類數據成員,static類數據成員獨立於一切類對象處在。static類數據成員是與類關聯的,但不與該類定義的對象有任何關係。即static不會像普通類數據成員一樣每一個類對象都有一份,全部類對象是共享一個static類成員的。例如A類對象修改了static成員爲1,那麼B對象對應的static類對象成員的值也會是1。
注意:static類對象必須要在類外進行初始化
class Text
{
public:
static int count;
};
int Text::count=0;//用static成員變量必須要初始化
int main()
{
Text t1;
cout<<t1.count<<endl;
return 0;
}//程序輸出0
static修飾的變量先於對象存在,所以static修飾的變量要在類外初始化。因爲static是所有對象共享的變量,必須要比對象先存在。
class Text
{
public:
static int count;
};
int Text::count=0;//用static成員變量必須要初始化
int main()
{
Text t1;
Text t2;
t1.count = 100; //t1對象把static成員count改爲100
cout<<t2.count<<endl; //當t2對象打印static成員的時候,顯示的是100而不是0
return 0;
}
好處:
用static修飾的成員變量在對象中是不佔內存的,因爲他不是跟對象一起在堆或者棧中生成,用static修飾的變量在靜態存儲區生成的。所以用static修飾一方面的好處是可以節省對象的內存空間。如同你創建100個Person對象,而這100個對象都有共有的一個變量,例如叫國籍變量,就是Person對象的國籍都是相同的。
2.static類成員函數
由於static修飾的類成員屬於類,不屬於對象,因此static類成員函數是沒有this指針的,this指針是指向本對象的指針。正因爲沒有this指針,所以static類成員函數不能訪問非static的類成員,只能訪問 static修飾的類成員。
class Text
{
public:
static int fun()
{
return num;
}
static int count;
int num;
};
int Text::count=5;//用static成員變量必須要初始化
int main()
{
Text t1;
Text t2;
t1.num=100;
t1.fun();//發生錯誤,fun函數return的是非static類成員 如果return count就正確
return 0;
}