ตัวอย่างการนับจำนวนออบเจ็กต์ของคลาสที่ถูกสร้างขึ้น โดยใช้ฟังก์ชันสมาชิก static (static member function)
หลักการ
- ข้อมูลสมาชิก static (
static int count) ถูกแบ่งปันโดยทุกออบเจ็กต์ของคลาส - ถ้าไม่กำหนดค่าเริ่มต้น จะถูกเริ่มต้นที่ 0 อัตโนมัติ
- ฟังก์ชันสมาชิก static สามารถเข้าถึงเฉพาะข้อมูลสมาชิก static ของคลาสนั้นๆ
การทำงาน
ใช้คลาส Student มี static int count นับจำนวนออบเจ็กต์ และ static void rollCall() แสดงจำนวนและเพิ่มค่า count
- Constructor เรียก
rollCall()และกำหนดrollno = count - Destructor ลดค่า
countลง 1 - ทุกครั้งที่สร้างออบเจ็กต์ count จะเพิ่มขึ้นและกำหนดให้ rollno
ตัวอย่างโค้ด C++
#include <iostream>
using namespace std;
class Student {
public:
int rollno;
static int count;
public:
Student() {
rollCall();
rollno = count;
}
~Student() { --count; }
static void rollCall(void) {
cout << endl << "Student Count: " << ++count << "\n";
}
};
int Student::count;
int main() {
Student stu1;
cout << "Student 1: Roll No: " << stu1.rollno;
Student stu2;
cout << "Student 2: Roll No: " << stu2.rollno;
Student stu3;
cout << "Student 3: Roll No: " << stu3.rollno;
Student stu4;
cout << "Student 4: Roll No: " << stu4.rollno;
return 0;
}
ผลลัพธ์
Student Count: 1 Student 1: Roll No: 1 Student Count: 2 Student 2: Roll No: 2 Student Count: 3 Student 3: Roll No: 3 Student Count: 4 Student 4: Roll No: 4