원 구현
Coddy C 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 45번째.
챌린지
쉬움Shape Drawer 프로젝트를 계속 구축하면서 Circle을 Implement해 보겠습니다. Shape은 base Shape struct를 embedded하고 자체적인 그리기 및 Area 로직을 제공하는 구체적인 shape입니다.
이전 lesson의 foundation을 바탕으로 다음 파일을 사용해 프로젝트를 확장합니다.
shape.h: 이전 lesson의 baseShapeinterface를 유지하고,DrawFunc및AreaFuncfunction pointer type을 포함합니다.circle.h: 여기에서Circlestruct를 Define합니다. Circle은Shape을 first member로 embedded하여 upcasting을 위한 first member rule을 활성화하고,doubletype의radiusfield를 추가합니다. radius를 인수로 받고 값으로Circle을 returns하는 constructor functioncreate_circle을 Declare합니다.circle.c: 여기에서 circle에 특화된 동작을 Implement합니다.draw_circle:Drawing Circle with radius: X.XX를 Prints합니다(radius는 소수점 이하 2자리로 표시).area_circle: π × radius²를 returns합니다(π에는3.14159를 사용).create_circle:Circle을 초기화하고, embeddedShape의 function pointer가draw_circle과area_circle을 가리키도록 연결하며, radius를 설정한 후 circle을 returns합니다.
main.c: 모든 요소를 함께 사용합니다. radius 값을 input으로 읽고, constructor를 사용해 circle을 Create한 다음, embeddedShape의 function pointer를 통해draw와area를 모두 Call합니다. Area를 소수점 이하 2자리로 Prints합니다.
프로그램은 하나의 input, 즉 radius 값(부동 소수점 수)을 받습니다.
input이 5.0일 때의 출력 예시:
Drawing Circle with radius: 5.00
Area: 78.54input이 3.5일 때의 출력 예시:
Drawing Circle with radius: 3.50
Area: 38.48핵심은 Circle이 Shape을 first member로 포함하므로, circle.base.draw와 circle.base.area(또는 embedded member에 지정한 이름)를 통해 function pointer에 access할 수 있다는 점입니다. 이러한 functions를 Call할 때는 Shape member를 가리키는 pointer를 전달합니다. 모든 header 파일에서 include guard를 사용하는 것을 잊지 마세요.
직접 해보기
#include <stdio.h>
#include "shape.h"
#include "circle.h"
int main() {
double radius;
scanf("%lf", &radius);
// TODO: create_circle을 사용하여 Circle 생성
// TODO: 임베디드 Shape의 함수 포인터를 통해 draw 호출
// TODO: 임베디드 Shape의 함수 포인터를 통해 area 호출
// 그리고 소수점 2자리로 출력: "Area: %.2f\n"
return 0;
}객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러