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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP