/*
定義靜態成員變量
1、關鍵字 static 可以用於說明一個類的成員
2、靜態成員提供了一個同類對象的共享機制
3、把一個類的成員說明爲 static 時,這個類無論有多少個對象被創建,
這些對象共享這個 static 成員
4、靜態成員局部於類,它不是對象成員
*/
#if 1
class counter
{
static int num; //聲明與定義靜態數據成員,默認是private
public:
void setnum(int i)
{
num = i;
}
void shownum()
{
cout << num << '\t';
}
};
//必須在類的外部對靜態成員進程初始化
//否則錯誤 2 error LNK2001
//int counter::num = 0;
void test()
{
counter a, b;
a.shownum();//調用成員函數訪問私有靜態數據成員
b.shownum();
a.setnum(10);
a.shownum();
b.shownum();
}
#endif
從結果可以看出,訪問的是同一個靜態數據成員
/*
如果不寫靜態函數的定義,當不用類定義對象時候,編譯不會報錯
只有定義類的對象時候,不寫的話纔會報錯
這是c++編譯器檢查不深!
*/
#if 0
class BB
{
int c0;//默認是private
public:
static int d; //使用公有靜態數據成員
void printC()//成員函數訪問靜態成員變量
{
cout << "c = " << c << endl;
}
void addC()
{
c = c + 1;
}
static void getC()
{
cout << "c = " << c << endl;
}
protected:
private:
int a;
int b;
static int c;//靜態成員變量
};
//int BB::c = 10; //屏蔽1
void test()
{
BB b1, b2, b3;
b1.getC();//屏蔽2 屏蔽1 2 竟然編譯通過
//打開屏蔽2 則不通過
//錯誤 5 error LNK2001: 無法解析的外部符號 "private: static int BB::c" (?c@BB@@0HA)
}
#endif
/*
==========static 靜態成員函數 和靜態成員變量=========
1、靜態成員函數數冠以關鍵字static;
2、靜態成員函數提供不依賴於類數據結構的共同操作,它沒有this指針;
3、在類外調用靜態成員函數用 “類名 :: ”作限定詞,或通過對象調用;
4、靜態成員函數屬於整個類的;
5、static修飾的變量,是屬於類,所有的對象都能共享使用;
6、靜態函數中 不能使用 普通成員變量 普通成員函數;
*/
#if 1
class BB
{
int c0;//默認是private
public:
static int d; //使用公有靜態數據成員
void printC()//成員函數訪問靜態成員變量
{
cout << "c = " << c << endl;
}
void addC()
{
c = c + 1;
}
//靜態成員函數
//c++編譯器無法確認是b1.a b2.a b3.a
static void getC()
{
cout << "c = " << c << endl;
//請問在靜態函數中,能調用 普通成員屬性或者 普通成員函數麼?
//cout << "a = " << a << endl;//error C2597: 對非靜態成員“BB::a”的非法引用
//普通成員a是屬於具體的某個對象的
//因爲靜態成員變量屬於整個類的,分不清楚普通成員變量是哪個具體對象的屬性
}
protected:
private:
int a;
int b;
static int c;//靜態成員變量
};
/*
如果不寫靜態函數的定義,當不用類定義對象時候,編譯不會報錯
只有定義類的對象時候,不寫的話纔會報錯
*/
int BB::c = 10; //必須在類外聲明與定義靜態數據成員
int BB::d = 11;
//static 修飾的變量,屬於類,所有的對象都能共享用
void test()
{
BB b1, b2, b3;
b1.printC(); //10
b2.addC(); //11
b3.printC(); //11 說明靜態變量是共用的
b3.getC();
//訪問公有靜態成員方法1
cout << "BB::d = " << BB::d << endl;
//訪問公有靜態成員方法2
cout << "b1.d = " << b1.d << endl;
//靜態成員函數 調用方法
b3.getC(); //用對象
BB::getC(); //類::
}
#endif