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

คลาสการจัดเก็บ static ใน C++

คลาสการจัดเก็บ static สั่งให้คอมไพเลอร์เก็บตัวแปร local ไว้ตลอดอายุของโปรแกรม แทนที่จะสร้างและทำลายทุกครั้งที่เข้าออก scope การทำให้ตัวแปร local เป็น static จึงทำให้พวกเขารักษาค่าระหว่างการเรียกฟังก์ชันได้

ตัวปรับแต่ง static ยังสามารถนำไปใช้กับตัวแปร global ได้ เมื่อทำเช่นนั้น จะทำให้ scope ของตัวแปรนั้นจำกัดอยู่ในไฟล์ที่ประกาศเท่านั้น

ใน C++ เมื่อใช้ static กับ class data member จะทำให้มีเพียงหนึ่งสำเนาของ member นั้นถูกแชร์โดย objects ทั้งหมดของคลาสนั้น

ตัวอย่าง

#include <iostream>
void func(void) {
    static int i = 10; // local static variable
    i++;
    std::cout << "i is " << i;
    std::cout << " and count is " << count << std::endl;
}
static int count = 6; /* Global variable */
int main() {
    while(count--) {
        func();
    }
}

ผลลัพธ์

โค้ดนี้จะให้ผลลัพธ์ดังนี้:

i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0