ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • C++ 연습문제 7.9
    C++ 2021. 10. 19. 18:38
    728x90
    반응형

    정사각형과 원을 동시에 표현할 수 있는 Shape 클래스를 만들어 보자. Shape 클래스는 멤버 변수로 정사각형 또는 원을 의미하는 타입 변수(int type_)를 가지고 있으며, double형 변수 하나(double len_)를 통해 정사각형의 경우 한 변의 길이를 나타내고 원의 경우 반지름을 나타내도록 하라. 생성자를 통해 타입과 한 변의 길이(반지름)를 지정할 수 있으며 멤버 함수로는 각 도형의 면적을 계산하는 GetArea 함수가 있다.

    이때 도형의 타입 값으로 정사각형은 1, 원은 2로 가정하라. 원의 면적 계산을 위한 PI 값은 const 멤버 변수로 선언하라. 그리고 현재 생성된 객체들 중 각 타입의 도형이 몇 개인지 알 수 있도록 static 멤버 변수를 사용해 보라.

    다음 main 함수와 실행 결과를 참고하라.

     

    main 함수 :

    int main() {
    	Shape shape1(1, 5);
    	Shape shape2(2, 5);
    	Shape* p_rect = new Shape[3];
    
    	cout << "사각형 개수    : " << Shape::GetRectCount() << endl;
    	cout << "원 개수        : " << Shape::GetCircleCount() << endl;
    	cout << "shape2의 면적  : " << shape1.GetArea() << endl;
    
    
    	delete[] p_rect;
    
    	cout << "사각형 개수    : " << Shape::GetRectCount() << endl;
    	cout << "원 개수        : " << Shape::GetCircleCount() << endl;
    	cout << "shape2의 면적  : " << shape2.GetArea() << endl;
    
    	return 0;
    }
    · 실행 결과

    사각형 개수       : 4
    원 개수             : 1
    shape1의 면적    : 25
    사각형 개수       : 1
    원 개수             : 1
    shape2의 면적    : 78.5

     

     

    내 코드(Shape.h) : 

    #include <iostream>
    using namespace std;
    
    class Shape {
    private:
    	int type_;
    	double len_;
    	const double PI;
    	static int reccnt;
    	static int circnt;
    
    public:
    	Shape(int type = 1, double len = 1) : type_(type), len_(len), PI(3.14) {
    		if (type_ == 1)
    			reccnt++;
    		else
    			circnt++;
    	}
    	~Shape() {
    		if (type_ == 1)
    			reccnt--;
    		else
    			circnt--;
    	}
    
    	double GetArea() const {
    		if (type_ == 1)
    			return (len_ * len_);
    		else
    			return (PI * len_ * len_);
    	}
    
    	static int GetRectCount() {
    		return reccnt;
    	}
    
    	static int GetCircleCount() {
    		return circnt;
    	}
    
    };
    
    int Shape::reccnt = 0;
    int Shape::circnt = 0;

     

    main.cpp : 

    #include "Shape.h"
    using namespace std;
    
    int main() {
    	Shape shape1(1, 5);
    	Shape shape2(2, 5);
    	Shape* p_rect = new Shape[3];
    
    	cout << "사각형 개수    : " << Shape::GetRectCount() << endl;
    	cout << "원 개수        : " << Shape::GetCircleCount() << endl;
    	cout << "shape2의 면적  : " << shape1.GetArea() << endl;
    
    
    	delete[] p_rect;
    
    	cout << "사각형 개수    : " << Shape::GetRectCount() << endl;
    	cout << "원 개수        : " << Shape::GetCircleCount() << endl;
    	cout << "shape2의 면적  : " << shape2.GetArea() << endl;
    
    	return 0;
    }
    728x90
    반응형

    'C++' 카테고리의 다른 글

    C++ 연습문제 9.2  (0) 2021.10.30
    C++ 연습문제 8.5  (0) 2021.10.30
    C++ 연습문제 7.4  (0) 2021.10.19
    C++ 연습문제 6.4  (0) 2021.10.19
    C++ 연습문제 2.23  (0) 2021.10.19
Designed by Tistory.