C++/C++17 中的內聯變數如何工作?


在 C++ 中,我們可為函式使用 inline 關鍵字。在 C++ 17 版本中,提出了 inline 變數的概念。

inline 變數允許在多個翻譯單元中定義。它也遵循單一定義規則。如果該定義多於一次,編譯器會將它們全部合併到最終程式中的一個物件中。

在 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

更新於:2019 年 7 月 30 日

3K+ 瀏覽量

職業生涯飛速開啟

完成課程獲得認證

開始
廣告