Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การ Define Static Members ใน C++

ภาพรวม

Static Members ใน C++ ประกอบด้วย Static Data Members และ Static Member Functions มีคุณสมบัติ:

  • เป็นของ Class** ไม่ใช่ของ Object แต่ละตัว
  • มีเพียง 1 Instance ในหน่วยความจำ (Shared)
  • Static Data: ต้อง Define นอกคลาส (Definition) ใน Global Scope
  • Static Functions: เรียกได้โดยไม่ต้องมี Object (ClassName::func())

Static Data Members

Declaration (ในคลาส)


class Point {
    int x, y;
public:
    static int count;  // Declaration Only!
};

Definition (นอกคลาส - ใน .cpp file)


// Point.cpp
int Point::count = 0;  // Definition + Initialization

C++17: Inline Static Members (Define ในคลาสได้เลย)


class ModernPoint {
    int x, y;
public:
    inline static int count = 0;  // Definition + Init ในคลาส!
    inline static const int MAX = 1000;
};

Static Member Functions

  • ไม่มี this Pointer
  • เข้าถึงได้เฉพาะ Static Members (Data/Functions)
  • เรียกผ่าน ClassName::func() หรือ obj.func()
  • ไม่สามารถเป็น virtual, const, volatile ได้

ตัวอย่างโค้ดครบถ้วน (Object Counter)


#include <iostream>
using namespace std;

class Point {
    int x, y;
public:
    static int count;  // Declaration
    
    Point(int x1 = 0, int y1 = 0) : x(x1), y(y1) {
        count++;  // Increment on Construction
    }
    
    ~Point() {
        count--;  // Decrement on Destruction
    }
    
    static void printCount() {
        cout << "Active Points: " << count << "\n";
    }
    
    void display() const {
        cout << "Point(" << x << ", " << y << ")\n";
    }
};

// Definition (Required Pre-C++17)
int Point::count = 0;

int main() {
    cout << "Initial count: ";
    Point::printCount();  // 0
    
    {
        Point p1(1, 2);
        Point p2(3, 4);
        Point::printCount();  // 2
        
        {
            Point p3(5, 6);
            Point::printCount();  // 3
        }  // p3 Destroyed
        
        Point::printCount();  // 2
    }  // p1, p2 Destroyed
    
    Point::printCount();  // 0
    return 0;
}

ผลลัพธ์


Initial count: Active Points: 0
Active Points: 2
Active Points: 3
Active Points: 2
Active Points: 0

Static Const Members (Special Rules)

TypeIn-Class InitOut-of-Class DefNote
static const int/enum✅ C++11❌ Not Needed**Unless ODR-used (address taken)
static constexpr✅ C++11❌ Not NeededImplicitly Inline
static const float/double❌ Pre-C++17✅ RequiredC++17: inline static OK
static const ClassType❌ Pre-C++17✅ RequiredC++17: inline static OK

การใช้งาน Static Members

  • Object Counting: Track Live Instances
  • Shared Configuration: Global Settings (Log Level, Cache Size)
  • Factory/Registry: Centralized Object Creation
  • Singleton Pattern: Meyers' Singleton ใช้ Function-Local Static ดีกว่า
  • Cache/Memoization: Shared Cache Across Instances

Thread Safety


#include 
#include 

class ThreadSafeCounter {
    static inline std::atomic count{0};  // C++17: Atomic + Inline
    static inline std::mutex mtx;             // For Complex Operations
    
public:
    static void increment() { count++; }  // Lock-free
    
    static int getAndIncrement() {
        std::lock_guard lock(mtx);
        return count++;
    }
};

ข้อควรระวัง

  1. Initialization Order Fiasco: Static Members ใน TU ต่างๆ ลำดับ Init ไม่แน่นอน
  2. Destruction Order: กลับกันกับ Initialization (ใน TU เดียวกัน)
  3. Static Initialization Order: ใช้ Function-Local Static (Meyers) แทน
  4. DLL/Shared Library: Static Members ต่อ TU/Module