본문 바로가기
개발/C++

[C++] static 멤버 변수, static 멤버 함수에 대해 (+ mutable)

by 램램이 2021. 8. 24.

static 멤버변수

 

기존 전역 변수를 사용 할 때

int a_num = 0;
int b_num = 0;

class A
{
public:
	void Plus_A() { a_num += 1; }
};

class B
{
	void Plus_B() { b_num += 1; }
};

int main()
{
	A a;
	B b;

	a.Plus_A();
	b.Plus_B();

	cout << a_num << ", " << b_num << endl;
}

위와 같이 선언 되어있으면, 특정 객체들만 사용할 수 있는 것이 아닌,

모든 객체들이 공통적으로 사용할 수 있게 된다.

이런 부분을 해결하고자 나온것이 static 멤버변수이다.

static 멤버변수는 일반적인 멤버변수와 달리 클래스당 하나씩만 생성된다.

 

static을 사용한 예제를 보면

class A
{
private:
	static int a_num;
public:
	void Plus_A() { a_num += 1; }
	void Show() {cout << a_num << endl;}
};
int A::a_num = 0;

class B
{
private:
	static int b_num;
public:
	void Plus_B() { b_num += 1; }
	void Show() {cout << b_num << endl;}
};
int B::b_num = 0; //외부에서 초기화를 해줘야한다

int main()
{
	A a;
	B b;

	a.Plus_A();
	b.Plus_B();

	a.Show();
	b.Show();
	
}

static 멤버변수는 항상 외부에서 초기화를 해야하는 것을 볼 수 있다. 

class의 멤버변수 이기 때문에 private로 선언 되어있으면 멤버 함수를 통해 호출해야한다.

public으로 선언하게 되면 바로 클래스의 이름을 사용하여 static 멤버변수에 접근할 수 있다.

 

...

int main()
{
	// static 변수에 바로 접근 가능
	cout << A::a_num << endl;
	cout << B::b_num << endl;
}

또한 위 코드를 보면 static 멤버변수에 바로 접근이 가능한 것을 볼수 있는데

이는 static 멤버 변수는 객체 내에 존재하지 않는 점을 알 수 있다.

 

클래스내에서 선언과 동시에 초기화를 하고 싶다면, const 키워드를 사용하여 해결할 수 있다.

class A
{
public:
	const static int a_num = 0;
		
	...

};

class B
{
public:
	const static int b_num = 0;

	...

}

 

static 멤버함수

static 멤버함수는 static 멤버 변수와 특성이 동일하다.

  • 선언된 클래스의 모든 객체가 공유한다.
  • public으로 선언되면, 클래스의 이름으로 호출 가능
  • 객체의 멤버로 존재하지 않는다.
class A
{
private:
	int num;
	static int num2;
public:
	A(int n) : num1(n) {}

	static void Adder(int n)
	{
		num1 += n; // 컴파일 에러
		num2 += n;
	}
};
int A::num2 = 0;

static 멤버 함수도 객체의 멤버로 존재하지 않기 때문에 멤버 변수에 접근이 불가능하다.

static 멤버 함수 내에서는 static 멤버 변수와 static 멤버 함수만 호출이 가능 ( static 끼리 가능 )

 

Mutable

Mutable은 const 함수 내에서 값 변경을 예외적으로 허용한다는 키워드이다.

class A
{
public:
	int num1;
	mutable int num2;
public:
	A(int n1, int n2) : num1(n1), num2(n2) {}
	
	void Change() const
	{
		num2 = 0; //const 함수지만 mutable로 선언된 num2값 변경
	}
}

주석의 설명과 동일하게 const 함수내에 있지만 const 변수가 아닌 변수 값의 변경이 가능하다.

댓글