본문 바로가기

Language/C++

정적 멤버변수와 정적 멤버함수

C++을 대충 했더니 다시 배워야 하는 불쌍사가.ㅠㅠ!!!!

기본 개념을 잡고 있다.

하는김에 포스팅도 함께 하기로 했다. ㅡ0ㅡ 귀찬지만 이렇게 하면 복습이 가능하니까.^^

정적 멤버변수와 정적 멤버 함수는 말은 먼가 있어 보이는데 실상은 결국 static 키워드로 치고 들어가는거다

별거 없다는걸 안순간 좀 뻥진다....

정적 멤버변수의 활용은 대표저으로 무엇인가를 count 할때 가장 많이 쓰인데

예를 들어서 학생 정보를 저장하는 클래스가 있는데 객체를 생성하고 저장할때 마다 학생수를 세는 cnt 변수가 있다고 가정을 하면..
#include "iostream"
#include<string.h>

using std::cout;
using std::endl;

class CStud
{
private:
    char name[30];
    char handphone[20];
    char email[30];
    int cnt;
public:
    CStud(char *n = "ㅡ.ㅡ",char *h = "010-1234-1234",char *e = "imagej@ncc.re.kr");
    ~CStud();
    void prn();
};
CStud::CStud(char *n, char *h,char *e)
{
    strcpy(name,n);
    strcpy(handphone,h);
    strcpy(email,e);

    cnt++;
}
CStud::~CStud()
{
    cnt--;
}
void CStud::prn()
{
    cout<<"이름 : "<<name<<endl;
    cout<<"핸드폰:"<<handphone<<endl;
    cout<<"이메일:"<<email<<endl;
    cout<<"현재까지 등록된 인원수 : "<<cnt<<endl;

}


void main()
{
    CStud man1("전수빈","019-2321-2131","abscke@ncc.re.kr");
    man1.prn();
    CStud man2("전원지","010-123-4323","mtmyjfi@hanvkd.con");
    man2.prn();
    CStud man3;
    man3.prn();
    cout<<"클래스의 할당된 메모리 사이즈:"<<sizeof(CStud)<<endl;

}
여기서 결과는 cnt가 3으로 나와야 하지만 전부 1로 나온다.
이유는 객체가 생설될때 마다 cnt라는 변수를 만들기 때문에 각자의 객체에서 생성된 cnt값이 동일하다.
 현재 객체가 3개 이므로 cnt가 3으로 나와야 하는데 이를 전역 변수로 선언을 해버리면 어디서든지 값이 바뀔수 있기 때문에 "정보화 은닉" 의 개념을 위반하는 것이 된다.

그러면 은닉을 할수 있고 객체끼리도 공유 할수 있는 방법은?
그렇다....static이다. 바로 정적 멤버변수...

#include "iostream"
#include<string.h>

using std::cout;
using std::endl;

class CStud
{
private:
    char name[30];
    char handphone[20];
    char email[30];
    static int cnt;
public:
    CStud(char *n = "조유창",char *h = "010-8512-5610",char *e = "imagej@ncc.re.kr");
    ~CStud();
    void prn();
};
int CStud::cnt = 0;//정적 멤버변수 초기화 (이거 매우중요!!)
CStud::CStud(char *n, char *h,char *e)
{
    strcpy(name,n);
    strcpy(handphone,h);
    strcpy(email,e);

    cnt++;
}
CStud::~CStud()
{
    cnt--;
}
void CStud::prn()
{
    cout<<"이름 : "<<name<<endl;
    cout<<"핸드폰:"<<handphone<<endl;
    cout<<"이메일:"<<email<<endl;
    cout<<"현재까지 등록된 인원수 : "<<cnt<<endl;

}

void main()
{
    CStud man1("전수빈","019-2321-2131","abscke@ncc.re.kr");
    man1.prn();
    CStud man2("전원지","010-123-4323","mtmyjfi@hanvkd.con");
    man2.prn();
    CStud man3;
    man3.prn();
    cout<<"클래스의 할당된 메모리 사이즈:"<<sizeof(CStud)<<endl;

}
이렇게 된다면  원하는 값 3이 cnt에서 출력이 된다. 이 이유는 정적 멤버변수는 객체가 생성될때 마다 생기는게 아니라 객체마다 같은 메모리를 공유하기 때문에 가능하다. 이는 멤버함수도 스타일이다. 객체를 생성할때 마다 생기는건 일반 멤버변수뿐 멤버함수는 하나의 함수가 메모리에 올라와서 객체들이 공유를 하게 된다. 어디서 호출되는지는 this point 가 묵시적으로 알아서 작용하기 때문임~

그러면 정적 멤버함수란?
정적 멤버함수란 c++서적에는 다음과 같이 타이틀이 정의 되어있다.
"정적 멤버변수의 접근을 위한 정적 멤버 함수"

솔직히 정적 멤버변수는 일반 객체로 접근을 할수가 있다. ㅡ.,ㅡ

이 정적 멤버함수의 특징은 객체가 없어도 호출이 가능하다는 점이다.
다음 예제를 보면...
#include "iostream"
#include<string.h>

using std::cout;
using std::endl;

class CStud
{
private:
    char name[30];
    char handphone[20];
    char email[30];
    static int cnt;
public:
    CStud(char *n = "조유창",char *h = "010-8512-5610",char *e = "imagej@ncc.re.kr");
    ~CStud();
    static void prn_cnt();//정적 멤버함수
    void prn();
};
int CStud::cnt = 0;
CStud::CStud(char *n, char *h,char *e)
{
    strcpy(name,n);
    strcpy(handphone,h);
    strcpy(email,e);

    cnt++;
}
CStud::~CStud()
{
    cnt--;
}
void CStud::prn()
{
    cout<<"이름 : "<<name<<endl;
    cout<<"핸드폰:"<<handphone<<endl;
    cout<<"이메일:"<<email<<endl;
    cout<<"현재까지 등록된 인원수 : "<<cnt<<endl;

}

void CStud::prn_cnt()
{
    cout<<"현재까지 등록된 인원수 : "<<cnt<<endl;
}
void main()
{
    CStud man1("전수빈","019-2321-2131","abscke@ncc.re.kr");
    man1.prn();
    CStud man2("전원지","010-123-4323","mtmyjfi@hanvkd.con");
    man2.prn();
    CStud man3;
    man3.prn();
    cout<<"클래스의 할당된 메모리 사이즈:"<<sizeof(CStud)<<endl;

    CStud::prn_cnt();//클래스의 영역에 있는 함수로 바로 호출

}
출력 OK 머 별거 없다.

응용을 어떻게 하느냐가 문제일뿐이다.

참고 : C++언어 30일 완성