본문으로 바로가기

OOP의 이해 - ③ static class

category Computer Science/C++ 2021. 10. 12. 16:56

OOP의 이해 - ③ static class

클래스에서 사용되는 static은 다음 3가지 종류가 있다.

  • static member function
  • static member variable
  • static variable in function

static member function

static member function은 클래스의 오브젝트가 생성되지 않아도 호출 가능하다. 그 이유는 static member function은 this 포인터와 바인딩되지 않기 때문이다. 그리고 static member function에서는 this 포인터와 바인딩되지 않기 때문에 멤버 변수에도 접근할 수 없다.

class cat{
public:
    cat();
    static void speak() 
    { 
        std::cout << "CAT!" << std::endl;
        std::cout << mAge << std::endl; // error
    }
private:
    int mAge;
};
int main()
{
    // 객체 생성 없이 호출 가능
    cat::speak();
    cat kitty;
    kitty.speak(); // 오브젝트에서 static 함수 호출도 가능
}

static member variable

static member variable는 static 메모리 영역에 할당되어 전체 클래스 오브젝트에서 유일한 변수를 공유하여 사용한다. 그래서 반드시 프로그램 실행 전에 초기화되어야 한다.

class cat{
public:
    cat();
    void speak() 
    { 
        coutn++;
        std::cout << count << "meow!" << std::endl;
    }
    static int count;
private:
    int mAge;
};
int cat::count = 0; // 초기화
int main()
{
    // 객체 생성 없이 호출 가능
    cat::speak();
    cat kitty;
    kitty.speak(); // 오브젝트에서 static 함수 호출도 가능
}

static variable in function

static member variable을 meber function에 넣게되면 동일하게 동작하지만, 사용자가 직접적으로 count에 접근하는 일을 막아주기 때문에 더 안전하게 사용할 수 있다.

class cat{
public:
    cat();
    void speak() 
    { 
        static int count = 0;
        coutn++;
        std::cout << count << "meow!" << std::endl;
    }
private:
    int mAge;
};

출처: https://www.youtube.com/channel/UCHcG02L6TSS-StkSbqVy6Fg