内联变量在 C++/C++17 中如何工作?

c++server side programmingprogramming

在 C++ 中,我们可以对函数使用 inline 关键字。在 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

相关文章