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

คีย์เวิร์ด static และการใช้งานต่างๆ ใน C++


คีย์เวิร์ด static ใน C++

เมื่อใช้ static ตัวแปร/สมาชิก/ฟังก์ชันจะไม่สามารถแก้ไขได้อีก จองหน่วยความจำตลอดอายุโปรแกรม Static function เรียกได้โดยตรงด้วยชื่อคลาส

Static variable เริ่มต้นเพียงครั้งเดียว Compiler เก็บตัวแปรจนจบโปรแกรม ประกาศได้ทั้งในและนอกฟังก์ชัน เป็น local ต่อบล็อก ค่าเริ่มต้นเป็นศูนย์ มีชีวิตจนโปรแกรมจบ

ไวยากรณ์

static datatype variable_name = value; // Static variable
static return_type function_name { // Static functions
    ...
}

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

class Base {
public:
    static int val;
    static int func(int a) {
        cout << "\nStatic member function is called";
        cout << "\nThe value of a: " << a;
    }
};

int Base::val = 28;

int main() {
    Base b;
    Base::func(8);
    cout << "\nThe static variable value: " << b.val;
    return 0;
}

ผลลัพธ์

Static member function is called
The value of a: 8
The static variable value: 28

ในโปรแกรม ประกาศ static variable และ static function ในคลาส Base เริ่มต้น static variable นอกคลาสก่อน main() เรียก static function โดยไม่ต้องสร้างออบเจ็กต์