日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C++靜態(tài)成員Static和單例設(shè)計模式

靜態(tài)成員

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

創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站設(shè)計制作、網(wǎng)站設(shè)計、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的鐵鋒網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

靜態(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)成員變量的一個重要應(yīng)用是統(tǒng)計一個類創(chuàng)建了多少對象。

計數(shù)器可以定義為靜態(tài)成員變量,每創(chuàng)建一個對象,在構(gòu)造函數(shù)中計算器+1,銷毀一個對象,將計數(shù)器-1。

#include 
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 
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;
}

分享文章:C++靜態(tài)成員Static和單例設(shè)計模式
本文路徑:http://www.dlmjj.cn/article/djdjhjg.html