static

2022. 4. 10. 12:35C++

c에서의 static

  • 전역변수에 선언된 static
    • 선언된 파일 내에서만 참조를 허용
  • 함수 내에 선언된 static
    • 한번만 초기화 되고, 지역변수와 달리 함수를 빠져나가도 소멸되지 않는다. 
#include <iostream>
using namespace std;

void Counter()
{
	static int cnt;
    cnt++;
    cout<<cnt;
}

int main(void)
{
	for(int i = 0; i <10; i++)
    	Counter();	// 12345678910 출력
    return 0;
}

 

전역변수가 필요한 상황

#include <iostream>
using namespace std;

int simObjCnt = 0;	// SoSimple 클래스를 위한 전역변수
int cmxObjCnt = 0;	// Socomplex 클래스를 위한 전역변수

class SoSimple
{
public: 
    SoSimple();
};

class SoComplex
{
public:
    SoComplex();
    SoComplex(SoComplex &copy);
};

int main(void){
    SoSimple sim1;
    SoSimple sim2;

    SoComplex com1;
    SoComplex com2 = com1;
    SoComplex();
}

SoSimple::SoSimple()
{
    simObjCnt++;
    cout<<"So Simple object: "<<simObjCnt<<endl;
}

SoComplex::SoComplex()
{
    cmxObjCnt++;
    cout<<"So complex object: "<<cmxObjCnt<<endl;
}

SoComplex::SoComplex(SoComplex &copy)
{
    cmxObjCnt++;
    cout<<"So complex object: "<<cmxObjCnt<<endl;
}

 

simObjCnt는 SoSimple 객체들이 공유하는 변수이고

comObjCnt는 SoComplex 객체들이 공유하는 변수이다. 

이 둘은 모두 전역변수이기 때문에 어디서든 접근 가능하다. 따라서 문제를 일으킬 소지가 매우 높다. 

 

static 멤버변수

satatic멤버 변수는 클래스 변수라고도 하며, 클래스당 하나씩만 생성된다. 

아래는 simObjCnt를 SoSimple클래스의 static변수로 선언한 예이다. 

class SoSimple
{
private:
	static int simObjCnt; //static 멤버변수, 클래스 변수
public: 
    SoSimple();
};

 

이렇게 SoSimple 클래스 안에 선언된 static변수는 모든 SoSimple객체가 공유하는 구조이고 생성 및 소멸의 시점도 전역변수와 동일하다. 

'C++' 카테고리의 다른 글

학번, 중간성적, 기말성적 입력 프로그램  (0) 2022.04.14
mutable  (0) 2022.04.10
friend  (0) 2022.04.10
연산자 오버로딩  (0) 2022.04.10
멤버 메서드의 선언, 정의 분리  (0) 2022.04.10