ใน C ++ เราสามารถใช้คำสำคัญแบบอินไลน์สำหรับฟังก์ชันได้ ในเวอร์ชัน C++ 17 แนวคิดตัวแปรอินไลน์ได้มาถึงแล้ว
ตัวแปรอินไลน์สามารถกำหนดได้ในหลายหน่วยการแปล นอกจากนี้ยังเป็นไปตามกฎคำจำกัดความเดียว หากมีการกำหนดไว้มากกว่าหนึ่งครั้ง คอมไพเลอร์จะรวมทั้งหมดเข้าเป็นอ็อบเจกต์เดียวในโปรแกรมสุดท้าย
ใน C++ (ก่อนเวอร์ชัน 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;
} ผลลัพธ์
The static value is: 10 In C++17, we can initialize the static variables inside the class using inline variables.
โค้ดตัวอย่าง
#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