需求
- 靜態
char ServerName 保存伺服器名稱
- 靜態
int ClientNum 記錄客戶數量
- 靜態函數
ChangeServerName() 修改名稱
- 分離宣告 (
client.h)、實作 (client.cpp)、測試 (test.cpp)
client.h
#ifndef CLIENT_H
#define CLIENT_H
class CLIENT {
public:
CLIENT(char name, int num); // 建構子同步更新靜態成員 (示範用)
~CLIENT();
static void ChangeServerName(char newName);
static char GetServerName();
static int GetClientNum();
private:
static char ServerName; // 僅宣告
static int ClientNum;
};
#endif
client.cpp (關鍵:定義靜態成員)
#include "client.h"
#include
// 靜態成員必須在全域/命名空間範圍定義並初始化
char CLIENT::ServerName = 'I';
int CLIENT::ClientNum = 0;
CLIENT::CLIENT(char name, int num) {
ServerName = name;
ClientNum = num;
}
CLIENT::~CLIENT() {}
void CLIENT::ChangeServerName(char newName) {
ServerName = newName;
}
char CLIENT::GetServerName() { return ServerName; }
int CLIENT::GetClientNum() { return ClientNum; }
test.cpp
#include "client.h"
#include
int main() {
CLIENT n('W', 7); // 建構子更新靜態值
std::cout << "Server: " << CLIENT::GetServerName() << "\n";
std::cout << "Clients: " << CLIENT::GetClientNum() << "\n";
CLIENT::ChangeServerName('X');
std::cout << "After change: " << CLIENT::GetServerName() << "\n";
return 0;
}
編譯指令
g++ client.cpp test.cpp -o test
./test
關鍵知識點
| 概念 | 說明 |
| 靜態成員宣告 | 類內 static type name; 僅宣告,不分配記憶體 |
| 靜態成員定義 | 類外 type Class::name = init; 分配記憶體,**僅一次** |
| 靜態成員函數 | 無 this 指標,僅能訪問靜態成員,可用 Class::func() 呼叫 |
| 建構子修改靜態值 | 每次建構物件都會覆蓋靜態值,通常靜態值由專門函數管理,建構子不宜修改 |