注:若沒有特指是 靜態成員時,默認都是普通成員;
1 類中的普通成員
類中的成員變數 和 成員函式 是分開存盤的,其中,
1)每個物件都有獨立的成員變數;成員變數可以存盤在 堆疊空間、堆空間、全域資料區;
2)所有物件共享類的成員函式;成員函式 只能存盤在 代碼段;
2 類中的靜態成員(static)
類中的靜態成員
1、用 static關鍵字 修飾;
2、可以用 類名::成員名 訪問 靜態成員;
3、靜態成員 屬于 整個類;
4、靜態成員 是所屬類的成員,其它類不能訪問;
5、靜態成員的記憶體分配 是 唯一的;
1) 靜態成員變數
特征:1、靜態成員變數 屬于 整個類所有;
2、靜態成員變數的生命周期不依賴任何物件;(靜態成員變數的生命周期在程式的運行期)
3、所有物件共享類的靜態成員變數;
4、可以通過 類名 直接訪問公有的靜態成員變數;
5、可以通過 物件名 訪問公有的靜態成員變數;
6、靜態成員變數 需要在類外單獨分配空間;(類內宣告、類外定義并初始化)
7、靜態成員變數 在程式內部位于全域資料區,不計入類的記憶體計算,
原因/好處:使用靜態成員變數實作多個物件之間的資料共享不會破壞隱藏的原則,保證了安全性還可以節省記憶體,
使用方法:
1、在類的內部,使用 static 修飾普通成員變數;
2、在類的外部(全域作用域),使用 Type ClassName::VarName = value 初始化,并申請存盤空間;
注:靜態成員變數不屬于類的任何物件,所以并不是物件建立時被定義的,所以它不能由類的建構式初始化,一般也不能在類內初始化;
1 /* 2 靜態成員變數 只能在類的內部宣告,在類的外部(全域區)定義和初始化; 3 */ 4 5 #include <iostream> 6 7 using namespace std; 8 9 class Test{ 10 public: 11 int GetA() const{return a;} 12 private: 13 static int a; // 靜態成員變數 14 }; 15 //int Test::a;如果這樣定義不賦予初值,則初值為零 16 int Test::a = 1; 17 18 int main(int argc, char *argv[]) 19 { 20 Test T; 21 22 cout << T.GetA() << endl; 23 24 return 0; 25 }
靜態成員變數 被類的所有物件共享,包括派生類物件;
1 #include <iostream> 2 3 using namespace std; 4 5 class Base{ 6 public: 7 static int a; // 靜態成員變數 8 }; 9 10 // int Test::a;如果這樣定義不賦予初值,則初值為零 11 int Base::a; 12 13 class Derived : public Base{ 14 15 }; 16 17 18 int main(int argc, char *argv[]) 19 { 20 Base B; 21 Derived D; 22 23 B.a++; 24 cout << B.a << endl; // 1 25 D.a++; 26 cout << D.a << endl; // 2 27 28 return 0; 29 }
靜態成員變數可以作為普通成員函式的默認形參,而普通成員變數則不可以;
1 class Test{ 2 public: 3 static int a; //靜態成員變數 4 int b; 5 void fun_1(int i = a); //正確 6 //void fun_2(int i = b); //報錯 7 };
靜態成員變數的型別 可以是所屬類的型別,而普通成員變數則不可以,普通成員變數只能宣告為 所屬型別別的 指標或參考;
1 class Test{ 2 public: 3 static Test a; //正確 4 Test b; //報錯 5 Test *pTest; //正確 6 Test &m_Test; //正確 7 static Test *pStaticObject; //正確 8 };
靜態成員變數在const函式中可以修改,而普通的成員變數是萬萬不能修改的;
1 /* 2 const修飾的是當前this指標所指向的物件是const,但是靜態成員變數不屬于任何類的物件,它被類的所有物件修改,所以this指標不修飾靜態的成員變數,所以可以更改, 3 */ 4 class Test{ 5 public: 6 static int a; 7 int b; 8 public: 9 Test():b(0){} 10 void test() const 11 { 12 a++; 13 //b++; // err // const指的是不能修改當前呼叫該函式物件的成員變數 14 } 15 }; 16 17 int Test::a;
2)靜態成員函式
特征:1、靜態成員函式 屬于 整個類所有;
2、所有物件共享類的靜態成員函式;
2、可以通過 類名 直接訪問公有的靜態成員函式;
3、可以通過 物件名 訪問公有的靜態成員函式;
4、靜態成員函式 只能 訪問靜態成員,不能訪問 非靜態成員;
5、靜態成員函式沒有this指標,也就是說靜態成員函式不能使用修飾符(也就是函式后面的const關鍵字);
原因:處理靜態成員變數;
使用方法:直接用 static 修飾 普通成員函式(類內宣告時),不需要 static 修飾(類外定義時);
總結:
案例分析:
1 /** 2 * 統計某班選修課考試的平均成績 3 */ 4 5 #include <iostream> 6 #include <string> 7 8 using namespace std; 9 10 class Student 11 { 12 private: 13 string name; // 姓名 14 string gender; // 性別 15 float score; // 分數 16 string subject; // 課程 17 static float chinese_scores; // 語文分數 18 static float math_scores; // 數學分數 19 public: 20 static int total_counts; // 總人數 21 static int chinese_counts; // 幼ò肝人數 22 static int math_counts; // 數學課人數 23 public: 24 Student(string name, string gender, float score, string subject); 25 ~Student(); 26 static float aveScores(string subject); 27 void printStudentInfo(); 28 void printAveScores(); 29 }; 30 int Student::total_counts = 0; 31 float Student::chinese_scores = 0; 32 int Student::chinese_counts = 0; 33 float Student::math_scores = 0; 34 int Student::math_counts = 0; 35 36 Student::Student(string name, string gender, float score, string subject) 37 { 38 this->name = name; 39 this->gender = gender; 40 this->score = score; 41 this->subject = subject; 42 43 if(subject == "chinese" || subject == "語文") 44 { 45 chinese_scores += score; 46 chinese_counts++; 47 } 48 else if(subject == "math" || subject == "數學") 49 { 50 math_scores += score; 51 math_counts++; 52 } 53 else 54 { 55 cout << "this is no the subect:" << subject << endl; 56 } 57 total_counts++; 58 } 59 60 Student::~Student() 61 { 62 total_counts--; 63 64 if(subject == "chinese" || subject == "語文") 65 { 66 chinese_counts--; 67 } 68 if(subject == "math" || subject == "數學") 69 { 70 math_counts--; 71 } 72 } 73 74 float Student::aveScores(string subject) 75 { 76 float ave_score = 0; 77 78 if(chinese_counts > 0 && subject == "chinese" || subject == "語文") 79 { 80 ave_score = (chinese_scores / chinese_counts); 81 //cout << subject << "\t" << chinese_counts << "\t" << chinese_scores << endl; 82 } 83 else if(math_counts > 0 && subject == "math" || subject == "數學") 84 { 85 ave_score = (math_scores / math_counts); 86 //cout << subject << "\t" <<math_counts << "\t" << math_scores << endl; 87 } 88 89 return ave_score; 90 } 91 92 void Student::printStudentInfo() 93 { 94 cout << name << "\t" << gender << "\t" << score << "\t" << subject << endl; 95 } 96 97 void Student::printAveScores() 98 { 99 cout <<subject << " average score: " << aveScores(subject) << endl; 100 } 101 102 void function() 103 { 104 const int SIZE = 5; 105 Student stu[SIZE] = 106 { 107 Student("10001", "male", 92, "語文"), 108 Student("10002", "male", 91, "數學"), 109 Student("10003", "male", 91, "數學"), 110 Student("10004", "male", 93, "語文"), 111 Student("10005", "male", 92, "語文"), 112 }; 113 114 for(int i = 0; i < SIZE; i++) 115 { 116 stu[i].printStudentInfo(); 117 } 118 119 stu[0].printAveScores(); 120 stu[1].printAveScores(); 121 122 cout << "語文" << " average score: " << Student::aveScores("語文") << endl; 123 cout << "數學" << " average score: " << Student::aveScores("數學") << endl; 124 125 cout << "總人數: " << Student::total_counts << endl; 126 } 127 128 int main(int argc, char const *argv[]) 129 { 130 function(); 131 132 cout << "幼ò肝人數: " << Student::chinese_counts << endl; 133 cout << "數學課人數: " << Student::math_counts << endl; 134 cout << "總人數: " << Student::total_counts << endl; 135 136 return 0; 137 }靜態成員的案例1
1 /** 2 * 案例:有一場籃球賽,紅隊與藍隊各有5名隊員,統計各個球隊的得分情況(總分、平均分),并將獲勝球隊的球員資訊輸出 3 */ 4 5 #include <iostream> 6 #include <string> 7 8 using namespace std; 9 10 class Player 11 { 12 public: 13 int number; // 編號 14 string gender; // 性別 15 int age; // 年齡 16 float score; // 個人分數 17 18 public: 19 Player(int number = 0, int age = 0, float score = 0, string gender = "male") 20 { 21 this->number = number; 22 this->age = age; 23 this->score = score; 24 this->gender = gender; 25 } 26 }; 27 28 class Team 29 { 30 private: 31 string name; // 球隊名稱 32 int sum; // 球隊總分 33 34 //static int COUNT; // 球隊人數 35 static const int COUNT = 5; // 球隊人數 36 Player player[COUNT]; // 球隊隊員資訊 37 public: 38 Team(string name) 39 { 40 this->name = name; 41 for(int i = 0; i < Team::COUNT; i++) 42 { 43 player[i] = Player(10001 + i, 20 + i, 0); 44 } 45 } 46 string getName() 47 { 48 return name; 49 } 50 static int playersCount() 51 { 52 return COUNT; 53 } 54 int totalScore() 55 { 56 sum = 0; 57 for(int i = 0; i < Team::COUNT; i++) 58 { 59 sum += player[i].score; 60 } 61 62 return sum; 63 } 64 float aveScore() 65 { 66 if(sum == 0) 67 { 68 totalScore(); 69 } 70 return (sum/Team::COUNT); 71 } 72 bool setPlayer(int index, int num, int age, float score, bool isMale = true) 73 { 74 bool ret = true; 75 76 if(Team::COUNT && index >= 0) 77 { 78 player[index].number = num; 79 player[index].age = age; 80 player[index].score = score; 81 isMale == true ? player[index].gender = "male" : player[index].gender = "female"; 82 } 83 else 84 { 85 cout << "the index of array is out of range, the max index should less than " << Team::COUNT << endl; 86 ret = false; 87 } 88 89 return ret; 90 } 91 bool PK(Team &team) 92 { 93 int ret = this->sum > team.sum; 94 95 if(ret) 96 { 97 cout << this->name + " 獲勝" << endl; 98 } 99 else 100 { 101 cout << team.name + " 獲勝" << endl; 102 } 103 104 return ret; 105 } 106 void print() 107 { 108 cout << "Team Name:" << name << endl; 109 for(int i = 0; i < Team::COUNT; i++) 110 { 111 cout << player[i].number << "\t" << player[i].gender << "\t" << player[i].age << "\t" << player[i].score << endl; 112 } 113 cout << name << " get total score:" << totalScore() << endl; 114 cout << name << " get average score:" << aveScore() << endl; 115 } 116 117 118 }; 119 //int Team::COUNT = 5; // 初始化每支球隊共有5名球員 120 121 122 123 int main(int argc, char *argv[]) 124 { 125 Team t1("Red Team"); 126 127 t1.setPlayer(0, 10001, 22, 91); 128 t1.setPlayer(1, 10003, 32, 93); 129 t1.setPlayer(2, 10005, 23, 94); 130 t1.setPlayer(3, 10007, 25, 95, false); 131 t1.setPlayer(4, 10009, 28, 88); 132 // t1.print(); 133 // cout << t1.getName() << " get total score:" << t1.totalScore() << endl; 134 // cout << t1.getName() << " get average score:" << t1.aveScore() << endl; 135 136 cout << endl; 137 138 Team t2("Blue Team"); 139 140 t2.setPlayer(0, 20001, 22, 81); 141 t2.setPlayer(1, 20003, 32, 83); 142 t2.setPlayer(2, 20005, 23, 84); 143 t2.setPlayer(3, 20007, 25, 85); 144 t2.setPlayer(4, 20009, 28, 88); 145 // t2.print(); 146 // cout << t2.getName() << " get total score:" << t2.totalScore() << endl; 147 // cout << t2.getName() << " get average score:" << t2.aveScore() << endl; 148 149 if( t1.PK(t2) ) 150 { 151 t1.print(); 152 } 153 else 154 { 155 t2.print(); 156 } 157 158 return 0; 159 }靜態成員的案例2
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/61726.html
標籤:C++
上一篇:求一個開發專案的學習路線
