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

วิธีสร้าง Static Class ใน C++

ภาพรวม

ใน C++ ไม่มีคีย์เวิร์ด static class โดยตรงเหมือน C# หรือ Java คลาสที่ใกล้เคียงที่สุดคือ คลาสที่มีเฉพาะ Static Data Members และ Static Member Functions เท่านั้น

คุณสมบัติของ Static Members

  • Static Data Members: แชร์ร่วมกันทุกออบเจ็กต์ของคลาส มีเพียง 1 ตัวในหน่วยความจำ ไม่ว่าจะสร้างออบเจ็กต์กี่ตัว
  • Static Member Functions: เรียกได้โดยไม่ต้องสร้างออบเจ็กต์ เข้าถึงได้เฉพาะ static members เท่านั้น

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

class Example {
public:
    static int a;           // Static data member
    
    static void func(int b) {  // Static member function
        cout << "Static member function called";
        cout << "\nThe value of b is: " << b;
    }
};

// ต้อง initialize static member นอกคลาส
int Example::a = 28;

int main() {
    Example obj;
    Example::func(8);  // เรียกผ่านชื่อคลาส ไม่ต้องสร้างออบเจ็กต์
    cout << "\nThe value of the static data member a is: " << obj.a;
    // หรือ Example::a ก็ได้
    return 0;
}

ผลลัพธ์

Static member function called
The value of b is: 8
The value of the static data member a is: 28

รายละเอียดการทำงาน

  1. static int a; ประกาศในคลาส แต่ ต้อง define/initialize นอกคลาส (int Example::a = 28;)
  2. static void func(int b) เรียกได้โดย Example::func(8) โดยไม่ต้องมีออบเจ็กต์
  3. ฟังก์ชัน static ไม่สามารถเข้าถึง non-static members ได้ (เพราะไม่มี this pointer)
  4. ออบเจ็กต์ obj สร้างขึ้นมา แต่ static member a ไม่ได้อยู่ในออบเจ็กต์

กรณีการใช้งาน (Use Cases)

  • นับจำนวนออบเจ็กต์ที่สร้าง (Counter)
  • เก็บค่าคงที่หรือการตั้งค่าร่วมกัน (Shared Configuration)
  • Factory Methods, Singleton Pattern
  • Utility Functions ที่ไม่ต้องการสถานะ (Stateless)

ข้อควรระวัง

  • Static members มีอายุชีวิตตลอดโปรแกรม (Global Lifetime)
  • Initialization order fiasco: static members ในไฟล์ต่างๆ อาจ initialize ในลำดับที่ไม่แน่นอน
  • Thread safety: การเข้าถึง static data จากหลาย thread ต้องใช้ mutex