ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • C++ 연습문제 11.6
    C++ 2021. 11. 20. 23:21
    728x90
    반응형

    [예제 11.9]에서 Shape 클래스를 추상 클래스로 만들어 보라. 그리고 Shape, Circle, Rect 클래스 모두 객체의 면적을 출력하기 위한 Print 함수를 추가하라. 이때 Shape 클래스의 경우 Print 함수를 순수 가상 함수로 선언하라. 마지막으로 Shape 클래스에 출력 연산자(<<) 오버로딩을 추가하라. 이것만으로 다음 main 함수가 실행 결과와 같이 수행될 수 있어야 한다. Shape 이외의 클래스에는 출력 연산자 오버로딩이 없다는 것에 주의하라.

     

    main.cpp : 

    #include <iostream>
    #include "class.h"
    using namespace std;
    
    int main() {
    	Circle cir(1, 1, 1);
    	Rect rect(2, 2, 2, 2);
    	Shape* p_spe;
    
    	p_spe = &cir;
    	cout << *p_spe;
    
    	p_spe = &rect;
    	cout << *p_spe;
    
    	return 0;
    }

     

     

    내 코드(class.h) : 

    #include <iostream>
    using namespace std;
    
    class Shape {
    public:
    	virtual void Print(ostream& out) const = 0;
    	friend ostream& operator<<(ostream& out, const Shape& s);
    };
    
    ostream& operator<<(ostream& out, const Shape& s) {
    	s.Print(out);
    	return out;
    };
    
    class Circle : public Shape {
    private:
    	int x_, y_;
    	double rad_;
    
    public:
    	Circle(int x, int y, double rad) : x_(x), y_(y), rad_(rad) {}
    	virtual void Print(ostream& out) const { cout << "원의 면적 : " << rad_ * rad_ * 3.14 << endl; }
    };
    
    class Rect : public Shape {
    private:
    	int x_, y_, w_, h_;
    
    public:
    	Rect(int x, int y, int w, int h) : x_(x), y_(y), w_(w), h_(h) {}
    	virtual void Print(ostream& out) const { cout << "사각형의 면적 : " << w_ * h_ << endl; }
    };
    728x90
    반응형

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

    C++ 연습문제 9.11  (0) 2021.11.07
    C++ 연습문제 9.8  (0) 2021.11.07
    C++ 연습문제 9.2  (0) 2021.10.30
    C++ 연습문제 8.5  (0) 2021.10.30
    C++ 연습문제 7.9  (0) 2021.10.19
Designed by Tistory.