Private Static Data Members** ต้อง Initialize นอก Class Definition (Definition) เหมือน Public Static Members แต่เข้าถึงได้เฉพาะ Member Functions และ Friends
Classic Syntax (Pre-C++17)
// MyClass.h
class MyClass {
private:
static int count_; // Declaration
static const int MAX = 100; // Const Integral: Initialize ใน Class ได้ (C++11)
public:
MyClass() { ++count_; }
static int getCount() { return count_; }
};
// MyClass.cpp (Definition ใน Translation Unit หนึ่ง)
int MyClass::count_ = 0; // Definition + Initialization
C++17 Inline Static Variables (Header-Only)
// MyClass.h (Header Only)
class MyClass {
private:
static inline int count_ = 0; // Definition + Init ใน Header
static inline const int MAX = 100; // Const
static inline std::string name_ = "Default"; // Complex Type OK
public:
MyClass() { ++count_; }
static int getCount() { return count_; }
static void setName(std::string n) { name_ = std::move(n); }
};
// ไม่ต้องมี .cpp File!
ตัวอย่างสมบูรณ์: Object Counter
#include <iostream>
#include <string>
class TrackedObject {
private:
static inline int instanceCount_ = 0; // C++17 Inline Static
static inline std::string lastCreated_ = "None";
const int id_;
public:
TrackedObject() : id_(++instanceCount_) {
lastCreated_ = "Object #" + std::to_string(id_);
std::cout << "Created: " << lastCreated_ << " (Total: " << instanceCount_ << ")\n";
}
~TrackedObject() {
std::cout << "Destroyed: Object #" << id_ << " (Remaining: " << --instanceCount_ << ")\n";
}
static int getCount() { return instanceCount_; }
static std::string getLastCreated() { return lastCreated_; }
int getId() const { return id_; }
};
int main() {
std::cout << "Start: " << TrackedObject::getCount() << '\n'; // 0
TrackedObject a; // #1
TrackedObject b; // #2
{
TrackedObject c; // #3
} // c Destroyed
std::cout << "End: " << TrackedObject::getCount() << '\n'; // 2
std::cout << "Last: " << TrackedObject::getLastCreated() << '\n';
}
ผลลัพธ์
Start: 0
Created: Object #1 (Total: 1)
Created: Object #2 (Total: 2)
Created: Object #3 (Total: 3)
Destroyed: Object #3 (Remaining: 2)
End: 2
Last: Object #3
Access Control: Private Static Members
- เข้าถึงได้: Member Functions, Friend Functions/Classes
- เข้าถึงไม่ได้: External Code (แม้จะเป็น Definition ใน .cpp)
- Exposing via Static Public Getters/Setters
Static Const Members: Special Cases
| Type | In-Class Init | Out-of-Class Definition |
|---|---|---|
static const int / Integral | ✅ C++11 | ❌ Not Needed (Unless ODR-Used: & taken) |
static const double / Float | ❌ Pre-C++17 | ✅ Required |
static constexpr (Any Literal) | ✅ C++11 | ❌ Not Needed (Implicit Inline) |
static inline (Any Type) | ✅ C++17 | ❌ Not Needed |
สรุป
Private Static Members ต้อง Define/Initialize นอก Class (Pre-C++17) C++17 static inline ทำให้ Header-Only Classes ง่ายขึ้น ใช้ constexpr สำหรับ Compile-time Constants mutable ไม่เกี่ยวกับ Static Members