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