본문 바로가기
코드

클래스 멤버 함수 포인터 사용 예제

by ehei 2010. 5. 13.

검색을 통해 발견할 수 있다. 그러나 워낙 힘들게 찾았기에 다른 사람들도 그러지 않을까 생각한다.  나만 해도 최근에 쓸 일이 있었는데, 일전에 정리한 샘플이 있었는데도 힘들었으니... 그나저나 정말 간만의 프로그램 글 업데이트다... 그 동안 얻은게 없는 건 아닌데. 예전에 오우거 공부할 때를 생각하면서 정리해봐야겠다.

//#include "stdafx.h"
#include < cstdio >
#include < cstdlib >

class Test
{
public:
    // 꼭 클래스 내부에 타입 정의를 해야한다
    typedef void (Test::*FunctionPointer)(int);

    Test() :
    _total(0)
    {}

    void Add(int value)
    {
        _total += value;
    }

    void Subtract(int value)
    {
        _total -= value;
    }

    int GetTotal() const
    {
        return _total;
    }

    // 함수 포인터를 비교해서 함수 이름을 반환한다
    const TCHAR* GetName(FunctionPointer functionPointer) const
    {
        if(&Test::Add == functionPointer)
        {
            return _T("Test::Add()");
        }
        else if(&Test::Subtract == functionPointer)
        {
            return _T("Test::Subtract");
        }

        return _T("Test::?");
    }

private:
    int _total;
};

int _tmain(int argc, _TCHAR* argv[])
{
    Test test;
    Test::FunctionPointer functionPointer = 0;

    // 인자가 1개 이상있으면 덧셈 함수를 실행한다
    if(0 < argc)
    {
        functionPointer = &Test::Add;
    }
    else
    {
        functionPointer = &Test::Subtract;
    }

    for(int i = 0; i < 100; ++i)
    {
        // 포인터 값을 구체화해서 인스턴스의 멤버 함수를 실행시킨다
        (test.*functionPointer)(i);
    }

    _tprintf(
        _T("total: %d (by %s)\n"),
        test.GetTotal(),
        test.GetName(functionPointer));
    system("pause");
    return 0;
}

'코드' 카테고리의 다른 글

googletest 사용하기  (0) 2010.06.29
libcurl 정적 링크 오류 해결하기  (0) 2010.05.20
CQ: Calculation Quotient  (0) 2006.11.19
V Player  (0) 2006.11.19
easyVNC 프로토타입  (0) 2006.10.18