關(guān)于C++靜態(tài)數(shù)據(jù)成員的實(shí)現(xiàn)講解
靜態(tài)數(shù)據(jù)成員是在一個(gè)類中用關(guān)鍵字static聲明的數(shù)據(jù)成員。在C++中,一般使用靜態(tài)成員來代替C語言的全局變量,以達(dá)到數(shù)據(jù)共享。C和C++的全局變量有一定的局限性,可以任意被修改,也容易和其它的變量名沖突,故在C++中,一般不使用全局變量。
靜態(tài)數(shù)據(jù)成員必須進(jìn)行初始化,初始化應(yīng)在類體外進(jìn)行,靜態(tài)數(shù)據(jù)成員也可以引用,但不能引用私有數(shù)據(jù)部分。
接下來看一個(gè)例子:
#include <iostream> #include <cstring> using namespace std ; class Student { private : //靜態(tài)成員變量 static int age ; static float score ; string name ; public : static int x , y ; //構(gòu)造函數(shù) Student(); //析構(gòu)函數(shù) ~Student(); //設(shè)置信息 int setstuinfo(int age , float score , string name); //打印信息 int Printstuinfo(); }; //靜態(tài)成員必須初始化 int Student::age = 24 ; float Student::score = 86.6 ; int Student::x = 100 ; int Student::y = 200 ; Student::Student() { this->name = "YYX" ; cout << this->name << endl ; cout << this->age << endl ; cout << this->score << endl ; } Student::~Student() { this->name = "NULL"; cout << this->name << endl ; } int Student::setstuinfo(int age , float score , string name) { this->age = age ; this->score = score ; this->name = name ; } int Student::Printstuinfo() { cout << this->name << endl ; cout << this->age << endl ; cout << this->score << endl ; } int main(void) { Student stu1 ; //指針 Student *p ; p = &stu1 ; p->setstuinfo(25,96,"XXX"); p->Printstuinfo(); //靜態(tài)成員的引用---->不可以引用私有成員 cout << p->x << endl ; cout << p->y << endl ; Student::x = 80 ; Student::y = 90 ; cout << p->x << endl ; cout << p->y << endl ; return 0 ; }
運(yùn)行結(jié)果:
YYX
24
86.6
XXX
25
96
100
200
80
90
NULL
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
C++使用string的大數(shù)取模運(yùn)算(5)
這篇文章主要為大家詳細(xì)介紹了C++使用string的大數(shù)取模運(yùn)算,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09c++獲取進(jìn)程信息列表和進(jìn)程所調(diào)用的dll列表
這篇文章主要介紹了c++獲取進(jìn)程信息列表和進(jìn)程所調(diào)用的dll列表,大家參考使用吧2013-11-11c++ 頭文件<cwchar>中常見函數(shù)的實(shí)現(xiàn)代碼
本文記錄了c++ 頭文件<cwchar>中常見函數(shù)的實(shí)現(xiàn),本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2023-12-12淺談c語言中轉(zhuǎn)義字符的用法及注意事項(xiàng)
下面小編就為大家?guī)硪黄獪\談c語言中轉(zhuǎn)義字符的用法及注意事項(xiàng)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-08-08C++實(shí)現(xiàn)快捷店會(huì)員管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)快捷店會(huì)員管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03