自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C++靜態(tài)成員Static和單例設(shè)計模式

開發(fā)
靜態(tài)成員是指被static修飾的成員變量或成員函數(shù),在程序運行過程中只占一份內(nèi)存,類似于全局變量,且也存儲在全局區(qū)。

靜態(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;
}
責任編輯:華軒 來源: 今日頭條
相關(guān)推薦

2015-09-06 11:07:52

C++設(shè)計模式單例模式

2010-02-05 17:00:06

C++單例模式

2021-02-01 10:01:58

設(shè)計模式 Java單例模式

2010-02-03 09:43:16

C++單例模式

2021-03-02 08:50:31

設(shè)計單例模式

2010-01-21 14:19:44

C++靜態(tài)成員

2010-01-27 10:45:21

C++單例模式

2013-11-26 16:20:26

Android設(shè)計模式

2016-03-28 10:23:11

Android設(shè)計單例

2010-01-21 14:28:03

C++靜態(tài)成員函數(shù)

2010-01-28 16:42:29

C++靜態(tài)成員

2010-01-18 18:04:28

靜態(tài)成員

2011-05-24 16:58:52

CC++

2024-12-30 11:12:59

C++靜態(tài)成員函數(shù)

2022-02-06 22:30:36

前端設(shè)計模式

2022-06-07 08:55:04

Golang單例模式語言

2023-10-07 15:53:05

C/C++靜態(tài)變量內(nèi)存

2024-02-22 18:07:17

C++靜態(tài)成員代碼

2010-01-18 17:57:02

靜態(tài)數(shù)據(jù)

2024-02-04 12:04:17

點贊
收藏

51CTO技術(shù)棧公眾號