国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C++ > 正文

關(guān)于C++靜態(tài)數(shù)據(jù)成員的實(shí)現(xiàn)講解

2020-01-26 13:36:42
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

靜態(tài)數(shù)據(jù)成員是在一個(gè)類中用關(guān)鍵字static聲明的數(shù)據(jù)成員。在C++中,一般使用靜態(tài)成員來(lái)代替C語(yǔ)言的全局變量,以達(dá)到數(shù)據(jù)共享。C和C++的全局變量有一定的局限性,可以任意被修改,也容易和其它的變量名沖突,故在C++中,一般不使用全局變量。

靜態(tài)數(shù)據(jù)成員必須進(jìn)行初始化,初始化應(yīng)在類體外進(jìn)行,靜態(tài)數(shù)據(jù)成員也可以引用,但不能引用私有數(shù)據(jù)部分。

接下來(lái)看一個(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ì)武林網(wǎng)的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 乐平市| 石林| 大庆市| 江达县| 潞城市| 大埔县| 绩溪县| 元阳县| 开原市| 乌兰察布市| 北京市| 崇文区| 六枝特区| 西乡县| 凌云县| 平舆县| 田林县| 塔城市| 涪陵区| 宁城县| 灵川县| 中牟县| 隆化县| 武定县| 昆明市| 南召县| 万安县| 辉南县| 崇文区| 博爱县| 富蕴县| 沭阳县| 辽源市| 崇阳县| 满城县| 建宁县| 五莲县| 盐源县| 乐至县| 额敏县| 青海省|