c++ static member 변수
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
'C++ > c++ - 따라하며 배우는 c++' 카테고리의 다른 글
c++ 친구 함수와 클래스 friend (0) | 2020.10.30 |
---|---|
c++ static member function (정적 멤버 함수) (0) | 2020.10.29 |
c++ class 와 const (0) | 2020.10.28 |
c++ 클래스 코드 와 헤더파일 (0) | 2020.10.28 |
c++ this포인터와 연쇄 호출 (0) | 2020.10.28 |
댓글
이 글 공유하기
다른 글
-
c++ 친구 함수와 클래스 friend
c++ 친구 함수와 클래스 friend
2020.10.30 -
c++ static member function (정적 멤버 함수)
c++ static member function (정적 멤버 함수)
2020.10.29 -
c++ class 와 const
c++ class 와 const
2020.10.28 -
c++ 클래스 코드 와 헤더파일
c++ 클래스 코드 와 헤더파일
2020.10.28