정적 멤버 변수 (Static Member Variable)
클래스 내부에
static
변수를 정의할 때는 직접 초기화할 수 없다.중복 선언 문제인 것 같다.
생성자에서도 초기화할 수 없다.
- Inner Class를 사용해서 우회하여 초기화할 수는 있다.
예제
static
이 아닌 기본 예제#include <iostream> class Something { public: int value_ = 1; }; int main() { using namespace std; Something st1; Something st2; st1.value_ = 2; cout << &st1.value_ << ' ' << st1.value_ << endl; cout << &st2.value_ << ' ' << st2.value_ << endl; } /* stdout 00CFFB4C 2 00CFFB40 1 */
static
예제#include <iostream> class Something { public: static int s_value_; }; int Something::s_value_ = 1; // define in .cpp file(not in header file) int main() { using namespace std; cout << &Something::s_value_ << ' ' << Something::s_value_ << endl; Something st1; Something st2; st1.s_value_ = 2; cout << &st1.s_value_ << ' ' << st1.s_value_ << endl; cout << &st2.s_value_ << ' ' << st2.s_value_ << endl; Something::s_value_ = 1024; cout << &Something::s_value_ << ' ' << Something::s_value_ << endl; } /* stdout 0032C008 1 0032C008 2 0032C008 2 0032C008 1024 */
- 클래스 외부에서 정의해야 한다는 점이 좀 헷갈린다.
Inner Class
Inner Class를 사용한
static
변수의 클래스 내부 초기화#include <iostream> class Something { public: class _init { public: _init() { s_value_ = 9876; } }; private: static int s_value_; static _init s_initializer; public: static int getValue() { return s_value_; } }; int Something::s_value_; Something::_init Something::s_initializer; int main() { using namespace std; Something s1; cout << s1.getValue() << endl; } /* stdout 9876 */
'C++ > Class' 카테고리의 다른 글
C++ friend (0) | 2021.03.16 |
---|---|
C++ 정적 멤버 함수 (Static Member Function) (0) | 2021.03.16 |
C++ static (Class) (0) | 2021.03.15 |
C++ 체이닝(Chaining) (0) | 2021.03.15 |
C++ this (0) | 2021.03.15 |