靜態(tài)成員

靜態(tài)成員是指被static修飾的成員變量或成員函數(shù),在程序運行過程中只占一份內(nèi)存,類?似于全局變量,且也存儲在全局區(qū)。
靜態(tài)成員變量邏輯上屬于類,可以通過類的權(quán)限控制靜態(tài)成員的訪問權(quán)限。
靜態(tài)成員函數(shù)內(nèi)部只能訪問靜態(tài)成員變量或函數(shù),因為靜態(tài)成員不依賴于對象的創(chuàng)建,所以也不可以通過this指針訪問。如果未創(chuàng)建對象,調(diào)用靜態(tài)成員函數(shù)里面訪問了非靜態(tài)函數(shù)或變量,邏輯上是行不通的。構(gòu)造函數(shù)和析構(gòu)函數(shù)也不可能是靜態(tài)的。
對象計數(shù)器
靜態(tài)成員變量的一個重要應用是統(tǒng)計一個類創(chuàng)建了多少對象。
計數(shù)器可以定義為靜態(tài)成員變量,每創(chuàng)建一個對象,在構(gòu)造函數(shù)中計算器+1,銷毀一個對象,將計數(shù)器-1。
#include <iostream>
using namespace std;
class Student {
private:
int m_id;
static int ms_count;
public:
static int get_count() {
return ms_count;
}
Student(int id = 0) : m_id(id) {
ms_count++;
}
~Student() {
ms_count--;
}
};
int Student::ms_count = 0;
int main() {
Student* stu1 = new Student(101);
cout << Student::get_count() << " " << stu1->get_count() << endl;
Student* stu2 = new Student(102);
cout << Student::get_count() << " " << stu1->get_count() << endl;
delete stu2;
cout << Student::get_count() << " " << stu1->get_count() << endl;
return 0;
}
單例設(shè)計模式
?在程序設(shè)計過程中,經(jīng)常會有只能創(chuàng)建一個實例的需求。比如,一個系統(tǒng)中可以存在多個打印任務(wù),但是只能有一個正在工作的任務(wù)。
單例設(shè)計模式可以借助static靜態(tài)成員實現(xiàn)。為了防止隨意創(chuàng)建或刪除對象,私有化構(gòu)造和析構(gòu)函數(shù),并使用類的私有靜態(tài)指針變量指向類的唯一實例,使用一個共有的靜態(tài)方法獲取該實例。?
#include <iostream>
using namespace std;
class Student {
private:
static int ms_id;
static Student* ms_stu;
Student(){}
~Student(){}
public:
static Student* createStudent(int id) {
if (ms_stu == NULL) {
ms_stu = new Student();
ms_id = id;
}
return ms_stu;
}
static void deleteStudent() {
if (ms_stu != NULL) {
delete ms_stu;
ms_id = -1;
}
}
static int getStudentId() {
return ms_id;
}
};
int Student::ms_id = -1;
Student* Student::ms_stu = NULL;
int main() {
Student* stu = Student::createStudent(101);
cout << stu->getStudentId() << endl;
stu->deleteStudent();
cout << stu->getStudentId() << endl;
return 0;
}