• 함수 포인터
    • 런타임에서 어떤 함수를 실행할 것인지 정하는 기능을 가지고 있음
      • C 에서는 함수포인터만 사용이 가능함, 당연히 C++에서도 사용이 가능함
      • C++ 에서는 polymorphism이 구현되면서 서브클래스의 메소드를 호출할 수 있음
      • C++11 에서는 람다 표현식이 추가되면서 코드 자체를 삽입할 수 있음
    • Example.1 옛날 버전의 C++을 사용하는 레거시 코드에서는 typedef 를 통해서 함수를 호출함
      • 클래스 내부의 함수 포인터는 약간 복잠함
#include <iostream>
using namespace std;

// case.1 일반적인 함수 포인터 + 네임스페이스 함수포인터
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
namespace UtilityNamespace {
	int devide(int a, int b) {
		return a / b;
	}
}
typedef int (*operation_1)(int a, int b);

// case.2 클래스 내부의 함수 포인터 : 인스턴스가 있어야 호출 가능
class Utility {
public:
	int multiply(int a, int b) {
		return a * b;
	}
};
typedef int (Utility::* operation_2)(int a, int b);


auto main() ->int {
	int a = 1;
	int b = 2;
	
	// case.1
	operation_1 op_1 = add;
	cout << op_1(a, b) << endl;
	op_1 = subtract;
	cout << op_1(a, b) << endl;
	op_1 = UtilityNamespace::devide;
	cout << op_1(a, b) << endl;

	// case.2
	operation_2 op_2 = &Utility::multiply;
	Utility util;
	cout << (util.*op_2)(a, b) << endl;
}

 

  • 보이드 포인터
    • Used to indicate a pointer to anything
    • Any kind of pointer(char*, Employee*, int*, ...) can be to void*
    • Pupular function parameter
    • Cast it back to what you know it is
복사했습니다!