[Hackerrank] C++ - 31 Rectangle Area

후유카와·2024년 11월 22일

Hackerrank

목록 보기
40/59

31. Rectangle Area

[ 난이도: Easy | 분야: Inheritance ]

1. 과제

이번 챌린지에서는, 사각형의 면적을 구해야 한다.

두 클래스를 만들자:

Rectangle

사각형 클래스는 두 데이터 필드를 가지고 있다 - int 형식의 width와 height

이 클래스는 display() 메소드를 가지고 있고, 이 메소드는 사각형의 넓이와 높이를 공백으로 구분하여 출력한다.

RectangleArea

RectangleArea 클래스는 Rectangle 클래스를 상속 받는다. 이 클래스는 read_input() 메소드를 가지고 있는데, 이 메소드는 사각형의 넓이와 높이를 읽어온다. RectangleArea 클래스는 display() 메소드를 오버로드하여 사각형의 면적을 출력한다.

입력 형식

단일 줄은 공백으로 구분된 두 정수를 가지고 있고 각각 넓이와 높이를 의미한다.

제약

넓이와 높이는 1보다 크거나 같고 100보다 작거나 같다.

출력 형식

출력은 두 줄로 이루어져 있다:

첫 번째 줄은 사각형의 넓이와 높이를 공백으로 구분하여 출력해라.

두 번째 줄은 사각형의 넓이를 출력해라.

입력 예시

10 5

출력 예시

10 5
50

설명

넓이가 10, 높이가 5이므로 면적은 50이다.

문제

#include <iostream>

using namespace std;
/*
 * Create classes Rectangle and RectangleArea
 */


int main()
{
    /*
     * Declare a RectangleArea object
     */
    RectangleArea r_area;
    
    /*
     * Read the width and height
     */
    r_area.read_input();
    
    /*
     * Print the width and height
     */
    r_area.Rectangle::display();
    
    /*
     * Print the area
     */
    r_area.display();
    
    return 0;
}

더보기

정답

#include <iostream>

using namespace std;
/*
 * Create classes Rectangle and RectangleArea
 */
 class Rectangle {
    public:
        int width;
        int height;
        virtual void display() {
            cout << width << " " << height << endl;
        }
 };
 
 class RectangleArea : public Rectangle {
    public:
        void read_input() {
            cin >> width >> height;
        }
        void display() {
            int area = width * height;
            cout << area << endl;
        }
 };


int main()
{
    /*
     * Declare a RectangleArea object
     */
    RectangleArea r_area;
    
    /*
     * Read the width and height
     */
    r_area.read_input();
    
    /*
     * Print the width and height
     */
    r_area.Rectangle::display();
    
    /*
     * Print the area
     */
    r_area.display();
    
    return 0;
}

주의!!

derived class에서 상위 클래스로 접근하기 위해서는 상위 클래스를 public으로 받아야 한다.

©️Hackerrank. All Rights Reserved.

profile
안녕하세요! 저는 전자공학을 전공하며 하드웨어와 소프트웨어 모두를 깊이 있게 공부하고 있는 후유카와입니다. Verilog HDL, C/C++, Java, Python 등 다양한 프로그래밍 언어를 다루고 있으며, 최근에는 알고리즘에 대한 학습에 집중하고 있습니다. 기술적인 내용을 공유하고, 함께 성장할 수 있는 공간이 되기를 바랍니다. 잘못된 내용이나 피드백은 언제나 환영합니다! 함께 소통하며 더 나은 지식을 쌓아가요. 감사합니다!

0개의 댓글