首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 靜態成員與構造函數錯誤修正:學生成績統計案例

     編輯:程式設計綜合問答

原代碼錯誤

  1. 構造函數未在類中聲明:Stud::Stud(int m, char n, float d) 定義在類外,但類內無對應聲明。
  2. 靜態成員函數訪問非靜態成員:static void disp() 中直接用 no、name、deg,編譯錯誤(靜態函數無 this 指針)。
  3. char name 只能存單字符,應為 char* name 或 std::string name。
  4. static int num 未在構造函數中自增,導致平均分計算分母為 0。

修正代碼

#include <iostream>
#include <string>
using namespace std;

class Stud {
private:
    int no;
    string name;          // 用 string 避免手動內存管理
    float deg;
    static float sum;
    static int count;     // 重命名避免與 num 衝突
public:
    Stud(int m, string n, float d); // 聲明構造函數
    static float avg();
    static void disp(const Stud* s); // 接收對象指針訪問非靜態成員
};

float Stud::sum = 0.0;
int Stud::count = 0;

Stud::Stud(int m, string n, float d) {
    no = m; name = n; deg = d;
    sum += deg;
    count++;
}

float Stud::avg() {
    return count ? sum / count : 0;
}

void Stud::disp(const Stud* s) {
    cout << "學號:" << s->no << endl;
    cout << "姓名:" << s->name << endl;
    cout << "成績:" << s->deg << endl;
    cout << "平均分:" << avg() << endl;
}

int main() {
    Stud s1(101, "Xiaoming", 84), s2(102, "Xiaohong", 94), s3(103, "Xiaofang", 87);
    s1.disp(&s1); s2.disp(&s2); s3.disp(&s3);
    return 0;
}

關鍵修正點

  • 構造函數類內聲明、類外定義。
  • 靜態函數 disp 接收 const Stud* 參數模擬 this,訪問實例成員。
  • count 在構造函數中自增,統計實例數量。
  • 使用 std::string 替代 char*,安全便捷。

此例展示了靜態成員統計全局信息、實例成員保存對象狀態的正確協作模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved