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

首頁 > 編程 > C++ > 正文

關于C++靜態數據成員的實現講解

2020-05-23 13:23:58
字體:
來源:轉載
供稿:網友

靜態數據成員是在一個類中用關鍵字static聲明的數據成員。在C++中,一般使用靜態成員來代替C語言的全局變量,以達到數據共享。C和C++的全局變量有一定的局限性,可以任意被修改,也容易和其它的變量名沖突,故在C++中,一般不使用全局變量。

靜態數據成員必須進行初始化,初始化應在類體外進行,靜態數據成員也可以引用,但不能引用私有數據部分。

接下來看一個例子:

#include <iostream>#include <cstring>using namespace std ; class Student { private : //靜態成員變量  static int age ; static float score ;  string name ; public : static int x , y ; //構造函數  Student(); //析構函數  ~Student();  //設置信息  int setstuinfo(int age , float score , string name); //打印信息  int Printstuinfo();};//靜態成員必須初始化 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(); //靜態成員的引用---->不可以引用私有成員 cout << p->x << endl ;  cout << p->y << endl ; Student::x = 80 ; Student::y = 90 ; cout << p->x << endl ;  cout << p->y << endl ; return 0 ;}

運行結果:

YYX
24 
86.6
XXX
25
96
100
200
80
90
NULL

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網的支持。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 崇仁县| 景德镇市| 清流县| 固始县| 略阳县| 灵川县| 越西县| 莆田市| 广宁县| 红河县| 西和县| 申扎县| 大埔县| 龙南县| 辽阳县| 金湖县| 陵川县| 都江堰市| 汤原县| 玉龙| 新郑市| 莎车县| 嵊州市| 乐昌市| 西和县| 桓仁| 吉林省| 闸北区| 吉隆县| 衡东县| 赫章县| 巴楚县| 嘉黎县| 林甸县| 江安县| 东宁县| 永吉县| 双城市| 女性| 霸州市| 沈阳市|