12.14 Static member functions

주홍영·2022년 3월 17일
0

Learncpp.com

목록 보기
138/199

https://www.learncpp.com/cpp-tutorial/static-member-functions/

Static member functions

저번 섹션에서 우리는 static member variable에 대해서 배웠다
우리는 static member variable이 object에 속한다기 보다
class 그 자체에 속한다는 것을 확인했었다
그리고 static member variable이 만약 public 영역에 있다면 direct 접근도 가능했다

그런데 만약 static member variable이 private 영역에 있으면 어떻게 할가?
example:

class Something
{
private:
    static int s_value;

};

int Something::s_value{ 1 }; // initializer, this is okay even though s_value is private since it's a definition

int main()
{
    // how do we access Something::s_value since it is private?
}

참고로 위 코드에서 s_value가 private 영역에 있지만
definition을 통해 initialize하는 것은 문제가 없다

위 코드에서 더 이상 s_value에 direct 접근은 할 수 없다
그렇다면 어떠한 방법으로 s_value를 사용해야 할가

일반적으로 public한 일반 function을 사용할 수는 있다
하지만 이렇게 하는 경우 우리는 object를 instantiate 해야한다는 번거로움이 있다

우리는 위와 같은 방법 대신 static member function을 통해 class direct로 함수를 호출할 수 있다

class Something
{
private:
    static int s_value;
public:
    static int getValue() { return s_value; } // static member function
};

int Something::s_value{ 1 }; // initializer

int main()
{
    std::cout << Something::getValue() << '\n';
}

static memver function인 getValue를 이용해
main 함수에서 Something::getValue()로 s_value에 접근해서 사용하고 있다
이렇게 static member variable 처럼 클래스 direct로 static member function을 호출할 수 있다

Static member functions have no *this pointer

static member function은 class attach로 this pointer가 없고 사용할 수 없다
다음으로 static member function은
can directly access other static members (variables or functions), but not non-static members

example

class IDGenerator
{
private:
    static int s_nextID; // Here's the declaration for a static member

public:
     static int getNextID(); // Here's the declaration for a static function
};

// Here's the definition of the static member outside the class.  Note we don't use the static keyword here.
// We'll start generating IDs at 1
int IDGenerator::s_nextID{ 1 };

// Here's the definition of the static function outside of the class.  Note we don't use the static keyword here.
int IDGenerator::getNextID() { return s_nextID++; }

int main()
{
    for (int count{ 0 }; count < 5; ++count)
        std::cout << "The next ID is: " << IDGenerator::getNextID() << '\n';

    return 0;
}

출력

The next ID is: 1
The next ID is: 2
The next ID is: 3
The next ID is: 4
The next ID is: 5

C++ does not support static constructors

몇몇 언어는 static constructor를 지원해 static member varialbe을 initialize할 수 있도록 지원해준다
하지만 c++은 그런 기능을 지원하지 않는다

따라서 c++에서 static member variable을 direct initialize를 해야 한다
다음 예제는 람다식을 활용해 char vector를 초기화 하고 있다

class MyClass
{
public:
    static std::vector<char> s_mychars;
};

std::vector<char> MyClass::s_mychars{
  []{ // The parameter list of lambdas without parameters can be omitted.
      // Inside the lambda we can declare another vector and use a loop.
      std::vector<char> v{};

      for (char ch{ 'a' }; ch <= 'z'; ++ch)
      {
          v.push_back(ch);
      }

      return v;
  }() // Call the lambda right away
};

위 코드에서 람다식 사용이 특이해 가져와 봤다
람다식 정의 맨 마지막에 ()를 붙여서 바로 호출하도록 하고 있다

profile
청룡동거주민

0개의 댓글