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

Inline Variables ใน C++17 ทำงานอย่างไร?

ใน C++ เราใช้คีย์เวิร์ด inline สำหรับฟังก์ชันมาแล้ว แต่ใน C++17 ได้นำแนวคิด inline variables มาใช้งาน

Inline variable อนุญาตให้กำหนดค่า (define) ใน translation units หลายแห่งพร้อมกัน และปฏิบัติตาม One Definition Rule (ODR) หากถูกกำหนดซ้ำ คอมไพเลอร์จะรวม (merge) ทั้งหมดเป็นอ็อบเจกต์เดียวในโปรแกรมสุดท้าย

ก่อน C++17 ไม่สามารถกำหนดค่า static member variable ภายในคลาสได้โดยตรง ต้องกำหนดภายนอกคลาส

โค้ดตัวอย่าง (ก่อน C++17)

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass() { ++num; }
    ~MyClass() { --num; }
    static int num;
};

int MyClass::num = 10; // ต้องกำหนดภายนอก

int main() {
    cout << "The static value is: " << MyClass::num;
}

โค้ดตัวอย่าง (C++17 ใช้ inline variable)

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass() { ++num; }
    ~MyClass() { --num; }
    inline static int num = 10; // กำหนดภายในคลาสได้เลย
};

int main() {
    cout << "The static value is: " << MyClass::num;
}

ผลลัพธ์

The static value is: 10