掌握 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 中調用)
• 主函數創建三個對象並輸出指定格式
static int count;,**類外必須定義並初始化** int Point::count = 0; (不加 static 關鍵字)static void showPoint();,類外定義 void Point::showPoint() {...},調用用 Point::showPoint() (不需對象)#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=3a.display() 等輸出各對象的 x 值 (非析構時調用,僅顯示)| 錯誤 | 後果 | 修正 |
|---|---|---|
類內初始化 static int count = 0; | C++98/03 編譯錯誤 (C++17 允許整型靜態常量) | 類外定義 int Point::count = 0; |
靜態函數中訪問 this 或非靜態成員 | 編譯錯誤 | 僅訪問靜態成員 |
忘記 static 關鍵字 | 變為普通成員,每對象一份副本 | 聲明定義處均加 static |
| 輸出格式多空格/少換行 | OJ 判題失敗 | 嚴格對照樣例,建議用 endl 而非 \n |
inline static 允許類內初始化:inline static int count = 0;count++/-- 需用 atomic 或鎖保護