클래스의 static 변수

2019. 8. 22. 10:26PL/C++

만일 static 변수는 클래스 내부에서 초기화는 불가능하다. 따라서 static 변수는 반드시 전역적으로 호출해서 초기화를 해줘야만 한다. 그리고 static 변수에 접근할 때는 특정 객체에서 접근하는 것이 아닌 class 전역적으로 접근한다(class이름::(static변수)). static 함수도 마찬가지다 

 

#include <iostream>

using namespace std;

class Simple {
private:
	static int num;
public:
	// static int num;
	Simple() {
		num += 1;
	}
	static void showNum() {
		cout << num << '\n';
	}
};

int Simple::num = 0;

int main(void) {
	Simple a, b, c, d;
	Simple::showNum();
	return 0;
}

 

[출처] https://studymake.tistory.com/295