Function Pointer In Class
C++ 클래스에서 함수 포인터 사용하기 ¶
1.1. 제약조건1 ¶예
class A
{ public: // 클래스 A에 대한 펑션 포인터 void (A::*FuncPtr)(void); void Func1(void) { cout<<"Func1"<<endl; } void Func2(void) { cout<<"Func2"<<endl; } void SetFuncPointer(int num) { if ( num == 1 ) this->FuncPtr = this->Func1; else this->FuncPtr = this->Func2; } void RunFuncPointer() { this->FuncPtr(); // <--- 컴파일 에러 발생 } }; 1.2. 제약조건2 ¶예
class A
{ public: void Func1(void) { cout<<"Func1"<<endl; } void Func2(void) { cout<<"Func2"<<endl; } }; int main() { A obj; // 클래스 A에 대한 펑션 포인터 변수 정의 void (A::*pf)(void); pf = obj.Func1; (obj.*pf)(); pf = obj.Func2; (obj.*pf)(); return 0; } 1.3. 제약조건3 ¶예
class A
{ private: void (*FuncPtr)(void); public: static void Func1(void) { cout<<"Func1"<<endl; } static void Func2(void) { cout<<"Func2"<<endl; } void SetFuncPointer(int num) { if ( num == 1 ) this->FuncPtr = this->Func1; else this->FuncPtr = this->Func2; } void RunFuncPointer() { this->FuncPtr(); } }; int main() { A obj; int num; cout<<"select function(1, 2) : "; cin>>num; obj.SetFuncPointer(num); obj.RunFuncPointer(); return 0; } |
It's not reality that's important, but how you percieve things. |