[ 난이도: Easy | 분야: Inheritance ]
이번 챌린지에서는, 사각형의 면적을 구해야 한다.
두 클래스를 만들자:
사각형 클래스는 두 데이터 필드를 가지고 있다 - int 형식의 width와 height
이 클래스는 display() 메소드를 가지고 있고, 이 메소드는 사각형의 넓이와 높이를 공백으로 구분하여 출력한다.
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.