본문 바로가기

IT 관련자료/C++

정적맴버 함수(static member function)

#include <iostream>


using namespace std;

class Something
{
    class _init
    {
    public:
        _init()
        {
            s_value = 9876;
        }
    };
private:


    static int s_value;
    int _value;

    static _init s_initializer;

public:
    


    Something()
        :_value(123) // , s_value(1234); static 생성자(constructor)를 생성할수 없다.
    {}

    static int getValue()
    {
        return s_value;
        //return _value; static아닌 변수 리턴 못함
        //return this->s_value; >> this=non-static member function에서만 사용가능
    }

    int temp()
    {
        //static 아닌 함수에서는 this사용 가능
        return this->s_value;
    }

};

int Something::s_value = 1024;
Something::_init Something::s_initializer;
int testint = 11;

int testfun()
{
    //class의 멤버 함수에서만 this 사용가능  
    //return this->testint;
    return 0;
}


int main()

{// 특정인스턴스(여기서는 s1)가 선언되지 않았을 때도 s_value에 접근이 가능하게 쓰는 방법
    // >> getValue 함수에 static 선언을 해줌...!
    cout << Something::getValue() << endl;
    Something s1, s2;
    cout << s1.getValue() << endl;
    //cout << s1.s_value << endl;

    //function pointer
    int (Something:: * fptr1)() = &Something::temp;

    //s2.*fptr1 Something이라는 클래스에 속해있는 멤버함수 temp의 포인터를 가지고 있는데 
    //이 포인터 위치에 있는 함수를 실행시킬때 s2라는 인스턴스에 포인터를 넘겨주고
    //s2라는 인스턴스에 this포인터를 가져다가 사용하는 형태로 작동
    //s2안주면 사용 못함 . nonstatic 멤버함수는 인스턴스에 종속되어있는 형태로 구현이 되어 있으니까
    //인스턴스가 없으면, this pointer가 없으면 작동을 못함, 결국은 내부에 모든게 this포인터가 생략이
    //되어있는형태. 다만 사용자의 편의를 위해 this포인터를 생략할 수 없다.

    //강사님이 ㅈㄴ길게 설명하셨지만 결국엔 nonstatic 멤버 함수는 인스턴스가 없으면 불러올 수 없다는걸
    //개념적으로 정확하게 잡아주려고 말하신듯... 일단은 안된다는 것만 알고 넘어가자.. 이해할 날이 오겠지.

    cout << (s2.*fptr1)() << endl;

    //함수의 포인터(function pointer) 값을 변수로 받을때 아래와 같이 선언
    //여기서 보면 Something::
    int (*fptr2)() = &Something::getValue;
    cout << fptr2() << endl;


    //테스트용. 클레스 안의 함수 말고 일반 함수에서도 적용 가능!!
    //function의 주소가 특정 인스턴스와 묶여있는게 아님
    int(*test_ptr)() = &testfun;
    cout << test_ptr() << endl;
    return 0;
}

'IT 관련자료 > C++' 카테고리의 다른 글

익명객체  (0) 2022.03.01
friend 함수  (0) 2022.02.28
class - 정적 맴버 변수(static)  (0) 2022.02.25
클래스와 const  (0) 2022.02.25
클래스코드와 헤더파일  (0) 2022.02.25