首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

SDUT 3-6 C++ 靜態數據成員與靜態成員函數實戰練習

     編輯:C++ 入門

實驗目的

掌握 C++ 中 static 數據成員(屬於類、不屬於對象)與靜態成員函數(無 this 指針、只能訪問靜態成員)的聲明、定義、初始化及用法。

題目要求

設計點類 Point:
• 數據成員:double x, y、static int count (記錄創建對象總數)
• 構造函數:Point(double a=0, double b=0),count++
• 析構函數:count--,輸出 Deconstructor point x=值
• 靜態成員函數 showPoint():輸出 x=0,Y=0 和 the number of points is count
• 普通成員函數 display():輸出析構信息 (題目要求在 main 中調用)
• 主函數創建三個對象並輸出指定格式

關鍵知識點

  1. 靜態數據成員:類內聲明 static int count;,**類外必須定義並初始化** int Point::count = 0; (不加 static 關鍵字)
  2. 靜態成員函數:類內聲明 static void showPoint();,類外定義 void Point::showPoint() {...},調用用 Point::showPoint() (不需對象)
  3. 構造/析構中操作 count:體現對象生命周期動態計數
  4. 輸出格式嚴格匹配:大小寫、標點、換行需與樣例完全一致

標準實現代碼

#include <iostream>
using namespace std;

class Point {
private:
    double x, y;
    static int count;          // 聲明靜態數據成員
public:
    static void showPoint();   // 聲明靜態成員函數
    void display() {           // 普通成員函數
        cout << "Deconstructor point x=" << x << endl;
    }
    Point(double a = 0, double b = 0) { // 構造函數
        count++;
        x = a; y = b;
    }
    ~Point() {                 // 析構函數
        count--;
    }
};

// 類外定義並初始化靜態數據成員
int Point::count = 0;

// 類外定義靜態成員函數
void Point::showPoint() {
    cout << "x=0,Y=0" << endl;
    cout << "the number of points is " << count << endl;
}

int main() {
    Point a(5), b(3), c(0);    // 創建三個對象,count=3
    Point::showPoint();        // 調用靜態函數
    a.display();               // 輸出析構信息 (對象未銷燬,但題目要求這樣調用)
    b.display();
    c.display();
    return 0;                  // main 結束,a,b,c 依次析構,count 歸零
}

運行輸出解析

x=0,Y=0
the number of points is 3
Deconstructor point x=5
Deconstructor point x=3
Deconstructor point x=0
  • Point::showPoint() 輸出固定格式,count=3
  • a.display() 等輸出各對象的 x 值 (非析構時調用,僅顯示)
  • 程序結束時棧上對象逆序析構:c(0)、b(3)、a(5),但樣例輸出順序為 5,3,0?實際 C++ 析構順序與創建順序相反,樣例可能簡化或錯誤。代碼邏輯正確即可。

常見錯誤避坑

錯誤後果修正
類內初始化 static int count = 0;C++98/03 編譯錯誤 (C++17 允許整型靜態常量)類外定義 int Point::count = 0;
靜態函數中訪問 this 或非靜態成員編譯錯誤僅訪問靜態成員
忘記 static 關鍵字變為普通成員,每對象一份副本聲明定義處均加 static
輸出格式多空格/少換行OJ 判題失敗嚴格對照樣例,建議用 endl 而非 \n

擴展思考

  • 靜態成員函數可作為線程同步計數器、單例模式工廠方法、工具類方法
  • C++17 inline static 允許類內初始化:inline static int count = 0;
  • 多線程環境下 count++/-- 需用 atomic 或鎖保護
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved