Menu
Coddy logo textTech

요약 - 도형 계산기

Coddy C++ 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 104개 중 63번째.

challenge icon

챌린지

쉬움

다형성에 대해 배운 모든 내용을 한데 모은 도형 계산기를 만들어 보겠습니다. 추상 Shape 클래스를 만들고, 공통 인터페이스를 통해 접근할 수 있으며 area와 perimeter를 계산하는 구체적인 도형을 Implement합니다.

코드를 네 개의 파일로 구성합니다:

  • Shape.h: 모든 도형의 청사진 역할을 하는 추상 Shape 클래스를 define합니다. 기본 클래스에는 다음이 있어야 합니다:
    • 도형을 식별하기 위한 protected std::string name member
    • name을 initializes하는 constructor
    • double을 반환하는 pure virtual method인 area()perimeter()
    • 도형의 name을 반환하는 getName() method
    • virtual destructor
  • Circle.h: Shape을 상속하는 Circle class를 Implement합니다:
    • private double radius member
    • radius를 받는 constructor (name을 "Circle"로 설정)
    • 다음 formula를 사용하여 area()를 Implement: 3.14159 * radius * radius
    • 다음을 사용하여 perimeter()를 Implement: 2 * 3.14159 * radius
  • Rectangle.h: Shape을 상속하는 Rectangle class를 Implement합니다:
    • private double widthdouble height member
    • width와 height를 받는 constructor (name을 "Rectangle"로 설정)
    • width * height로 area()를 Implement
    • 2 * (width + height)로 perimeter()를 Implement
  • main.cpp: 네 개의 inputs를 읽습니다(각각 별도의 줄에 입력):
    1. Circle radius (double)
    2. Rectangle width (double)
    3. Rectangle height (double)
    4. 두 번째 Circle radius (double)

    세 개의 도형을 모두 dynamically Create하고 Shape* pointers의 array에 저장합니다. array를 Loop하며 각 도형에 대해 다음 Format으로 정보를 print합니다:

    <name>:
      Area: <area>
      Perimeter: <perimeter>

    각 도형 사이에 blank line을 print합니다. 작업이 끝나면 dynamically allocated objects를 Clean합니다.

예를 들어 inputs가 5, 4, 6, 3인 경우:

Circle:
  Area: 78.5397
  Perimeter: 31.4159

Rectangle:
  Area: 24
  Perimeter: 20

Circle:
  Area: 28.2743
  Perimeter: 18.8495

동일한 printShapeInfo 로직이 모든 도형 type에 대해 작동하는 것을 확인하세요. 이것이 바로 다형성의 power입니다. 코드는 Shape interface를 통해 Circle과 Rectangle을 동일한 방식으로 처리하고, 각 도형은 자신의 측정값을 계산하는 방법을 알고 있습니다. 올바른 function signatures를 보장하려면 override된 모든 method에 override keyword를 사용하세요.

직접 해보기

#include <iostream>
#include "Shape.h"
#include "Circle.h"
#include "Rectangle.h"

using namespace std;

int main() {
    // 입력 읽기
    double circleRadius1, rectWidth, rectHeight, circleRadius2;
    cin >> circleRadius1;
    cin >> rectWidth;
    cin >> rectHeight;
    cin >> circleRadius2;

    // TODO: Shape* 포인터 배열을 3개 요소로 생성
    // Shape* shapes[3];

    // TODO: 도형을 동적으로 생성하고 배열에 저장
    // shapes[0] = new Circle(...);
    // shapes[1] = new Rectangle(...);
    // shapes[2] = new Circle(...);

    // TODO: 배열을 순회하며 각 도형의 정보를 출력
    // 형식:
    // <name>:
    //   Area: <area>
    //   Perimeter: <perimeter>
    // (도형들 사이에 빈 줄, 하지만 마지막 뒤에는 없음)

    // TODO: 동적으로 할당된 객체 정리
    // delete shapes[i];

    return 0;
}

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러