728x90
class Something
{
public:
	static int s_value;
}; 

int Something::s_value = 1;

int main()
{
	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;
	return 0;
}
    

 

 

static member 변수는 class 안에서 선언은 가능하지만 초기화를 할 수 없습니다.

 

 

int Something::s_value = 1;

 

 

밖에서 s_value 를 1로 초기화하고

 

 

	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;

 

 

메모리 주소 값과 value 값을 출력합니다.

 

 

 

class 안에서 static member 변수를 초기화하는 방법이 있는데 const를 사용하는 것입니다.

 

class Something
{
public:
    static const int s_value = 1;
};

 

static const 일 경우 class 안에서 초기화가 가능합니다. 반대로 클래스 밖에서는 초기화가 불가능합니다.

반드시 클래스 안에서 초기화를 해야 합니다.

 

const와 constexpr 이 있는데 const는 런타임에 값이 결정될 수도 있는 반면 constexpr 은 

컴파일 타임에 확실히 값이 결정돼야 합니다.

 

* static member 일 경우 cpp 파일 안에서 정의하는 게 좋습니다 *

* 헤더 파일 안에서 정의할 경우 컴파일 에러가 발생합니다 *

728x90