클래스를 활용한 간단한 문제
사각형 클래스
직사각형의 정보를 가지고 출력해주는 클래스를 작성해 봅시다.
명세서
멤버변수
int width : 가로길이
int height : 세로길이
멤버함수(메서드)
- 가로길이와 세로길이를 세팅, 리턴하는 세터(setter)/게터(getter) 메소드
- 사각형의 넓이를 리턴하는 area 메소드
- 정사각형인지 확인해서 리턴해주는 is_square 메소드
메인함수
int main(){
Rectangle rect1, rect2;
rect1.set_width(10);
rect1.set_height(20);
rect2.set_width(150);
rect2.set_height(150);
if(rect1.is_square()) cout << "rect1 is Sqaure" << endl;
if(rect2.is_square()) cout << "rect2 is Sqaure" << endl;
cout << "Area of rect1 is : " << rect1.area() << endl;
cout << "Area of rect2 is : " << rect2.area() << endl;
}
입력예시
X
출력결과
소스코드
더보기
#include <iostream>
using namespace std;
class Rectangle{
private:
int width;
int height;
public:
void set_width(int w);
void set_height(int h);
int get_width();
int get_height();
int area();
bool is_square();
};
// 구현부
void Rectangle::set_width(int w) { width = w; }
void Rectangle::set_height(int h) { height = h; }
int Rectangle::get_width() { return width; }
int Rectangle::get_height() { return height; }
int Rectangle::area(){
return width * height;
}
bool Rectangle::is_square(){
if (width == height) return true;
return false;
}
Check Point!
더보기
- getter 함수를 이용해서 두 사각형을 더해보세요
- 반지름 멤버변수를 가지고있는 원(circle) 클래스도 만들어보세요
'C++ 독학 > [C++ 독학] 프로젝트' 카테고리의 다른 글
[C++ 독학] 평균과 등급 구하기 <프로젝트 03> (0) | 2022.07.07 |
---|---|
[C++ 독학] 사원 정보 저장 <프로젝트 02> (0) | 2022.03.13 |
[C++ 독학] 정보를 출력해보자! <프로젝트 01> (0) | 2022.03.06 |
댓글