ที่นี่เราจะดูวิธีการเริ่มต้นการเริ่มต้นตัวแปรสมาชิกแบบคงที่ใน C ++ เราสามารถใส่สมาชิกแบบคงที่ (ฟังก์ชันหรือตัวแปร) ในคลาส C++ สำหรับตัวแปรสแตติก เราต้องเริ่มต้นพวกมันหลังจากกำหนดคลาสแล้ว
ในการเริ่มต้นเราต้องใช้ชื่อคลาส จากนั้นตัวดำเนินการแก้ไขขอบเขต ตามด้วยชื่อตัวแปร ตอนนี้เราสามารถกำหนดค่าบางอย่างได้
รหัสต่อไปนี้จะแสดงเทคนิคการเริ่มต้นสมาชิกแบบคงที่
ตัวอย่าง
#include <iostream>
using namespace std;
class MyClass{
private:
static int st_var;
public:
MyClass() {
st_var++; //increase the value of st_var when new object is created
}
static int getStaticVar() {
return st_var;
}
};
int MyClass::st_var = 0; //initializing the static int
main() {
MyClass ob1, ob2, ob3; //three objects are created
cout << "Number of objects: " << MyClass::getStaticVar();
} ผลลัพธ์
Number of objects: 3