✅ 목표 (Goal)

이번 시간에는 구조체 내에 함수 포인터를 멤버 변수(?)로 가진후 구조체 내에서 호출해보자.

Untitled

#include <stdio.h>
#include <conio.h>
#include "four_arith_op.h"

typedef struct _calculator_t {
	int (*op)(int a, int b);
} calculator_t;
typedef int (*fp_calc)(int, int);

int main() {
	calculator_t calculator;
	calculator.op = &add;

	int a = 7;
	int b = 3;
	float r = 0;

	r = calculator.op(a, b);

	printf("%d%c%d=%3.1f\\r\\n", a, '+', b, (float)r);

	return 0;
}

여기서 주의깊게 볼 부분은, 아래 코드인데, 마치 OOP의 클래스 멤버 함수를 호출하는 것과 같이 사용할수가 있다.

r = calculator.op(a, b);

위 내용을 잘 이해했다면, 분명 다음과 같이 하고 싶을것이다.

calculator.add(a, b);
calculator.sub(a, b);
calculator.mul(a, b);

요롷게 하면 된다.

Untitled