C++ 学生类
學生類——靜態數據成員和靜態成員函數
題目描述
定義一個類Student,要求使用靜態數據成員或靜態成員函數計算全班學生的《計算機導論》課程的總成績和平均成績。
靜態數據成員:static int total;
靜態成員函數:static void Average(){}
輸入描述
學生姓名 課程成績
輸出描述
總成績和平均成績
輸入樣例
Zhang 82 Li 79 Wang 93 Liu 66 Xia 90輸出樣例
410 82程序代碼
#include <iostream> #include <cstring>using namespace std;class Student {private:double m_score; // 學生分數char m_name[64];// 統計學生個數的靜態成員變量static int m_count;// 統計學生總分數的靜態成員變量static double sum_score;public:Student() {}Student(char *name ,double score) {// 創建一個學生m_score = score;m_count++; // 對創建的學生對象的人數進行累加 sum_score += score; // 對創建的學生對象的分數進行累加 strcpy(m_name, name);}static double Average() { // 提供一個訪問平均分的靜態方法 return sum_score / m_count;}static double getSumScore() { // 提供一個訪問總分的靜態方法 return sum_score;}~Student() {m_count--; // 每析構一個對象,數量減去一 sum_score -= m_score; // 析構一個對象,減去對象對應的學生分數 } };int Student::m_count = 0; // 對靜態變量進行初始化 double Student::sum_score = 0.0; // 對靜態變量進行初始化 int main(){Student *s1 = new Student("Zhang", 82);Student *s2 = new Student("Li", 79);Student *s3 = new Student("Wang", 93);Student *s4 = new Student("Liu", 66);Student *s5 = new Student("Xia", 90);cout << Student::getSumScore() << endl;cout << Student::Average() << endl;delete s5; delete s4;delete s3;delete s2;delete s1;return 0; }學生成績高低——友元函數
題目描述
在第一題的基礎上,設計一個友元函數,比較某兩個學生成績的高低。
輸入描述
學生姓名和分數
輸出描述
分數高低的結果(>或<或==)
輸入樣例
zhang 92 li 89輸出樣例
>程序代碼
#include <iostream> #include <string.h>using namespace std;class Student{private:int m_score; // 分數 char * m_name; // 姓名 public:Student(const char * n, int score);//構造函數friend char Compare(const Student stu1, const Student stu2);~Student(); Student(); };Student::Student(const char * name, int score){//構造函數int len = strlen(name);m_name = new char[len+1];strcpy(m_name, name);m_score = score; }Student::~Student() { if (m_name != NULL) {m_name = NULL;}}char Compare(const Student stu1, const Student stu2){ // 比較某兩個學生成績的高低 if(stu1.m_score > stu2.m_score) {return('>');} else if (stu1.m_score < stu2.m_score){return('<');} else {return('=');} }int main(){char name[64]; int score;cin >> name >> score;Student *stu1 = new Student(name, score); // 創建對象 cin >> name >> score;Student *stu2 = new Student(name, score); // 創建對象 cout << Compare(*stu1, *stu2) << endl; // 輸出結果 delete stu1;delete stu2;return 0; }總結
- 上一篇: C++ 使用静态变量和静态方法统计学生分
- 下一篇: C++ 设计员工类(Employee)