본문 바로가기
C++ 독학/[C++ 독학] 프로젝트

[C++ 독학] 사각형 객체를 만들어보자

by NpsCause 2023. 1. 5.

클래스를 활용한 간단한 문제

사각형 클래스

직사각형의 정보를 가지고 출력해주는 클래스를 작성해 봅시다.

 

명세서

멤버변수

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) 클래스도 만들어보세요

댓글