250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/8.11] 클래스와 static function and inner class, 정적 함수와 내부 함수 본문

C++/따배C++ 08강 객체지향 기초

[C++/8.11] 클래스와 static function and inner class, 정적 함수와 내부 함수

polarcompass 2021. 10. 25. 03:34
728x90

static은 this-> 포인터 사용 불가.

class 내부 함수는 특정 instance에 묶여있지 않다.

#include <iostream>
using namespace std;

class Something
{
public:
    // inner class
    class _init
    {
    public:
        //inner class 생성자
        _init()
        {
            s_value = 9876;
        }
    };

private:
    static int s_value;
    int m_value;

    static _init s_initializer;

public:
    // 특정 instance 없이도
    // s_value에 접근 가능하도록
    // 함수 앞에 static을 붙여준다.
    static int getValue()
    {
        //static은 this-> 를 사용하지 못함.
        return s_value;
        // return m_value;
        // 접근못함.
    }

    int temp()
    {
        return this->s_value;
    }
};

// s_value 초기화
int Something::s_value = 2024;
// 초기화 클래스 함수
Something::_init Something::s_initializer;

int main()
{
    cout << Something::getValue() << endl;

    Something s1, s2;
    cout << s1.getValue() << endl;
    // cout << s1.getValue() << endl;

    int (Something::*fptr1)() = &Something::temp;
    // *fptr1은 temp함수의 포인터이고, s2라는 instance의 this->
    // 포인터를 넘겨받아 temp함수를 작동시키게 된다.
    // 따라서 s2가 없으면 *fptr1이 작동이 안되게 된다.
    cout << (s2.*fptr1)() << endl;

    int (*fptr2)() = &Something::getValue;
    cout << fptr2() << endl;
    // function은 특정 s1,s2 같은 instance에 묶여있지 않다.

    return 0;
}
728x90