Search
Duplicate
🔢

9장. 실습문제

생성일
2022/05/11 02:04
태그
C++

9장. 실습문제

1.
위의 Shape 클래스를 상속받아 타원을 표현하는 Oval, 사각형을 표현하는 Rect, 삼각형을 표현하는 Triangular 클래스를 작성하라.
#include <iostream> using namespace std; class Shape { protected: string name; int width, height; public: Shape(string n="", int w = 0, int h = 0) { name = n; width = w; height = h; } virtual double getArea() { return 0; } string getName() { return name; } }; class Oval : public Shape { public: Oval(string n, int w, int h) : Shape(n, w, h){;} virtual double getArea() { return 3.14 * width * height; } }; class Rect : public Shape { public: Rect(string n, int w, int h) : Shape(n, w, h){;} virtual double getArea() { return width * height; } }; class Triangular : public Shape { public: Triangular(string n, int w, int h) : Shape(n, w, h){;} virtual double getArea() { return (width * height) / 2; } }; int main() { Shape *p[3]; p[0] = new Oval("빈대떡", 10, 20); p[1] = new Rect("찰떡", 30, 40); p[2] = new Triangular("토스트", 30, 40); for (int i = 0; i < 3; i++) cout << p[i]->getName() << " 넓이는 " << p[i]->getArea() << endl; for (int i = 0; i < 3; i++) delete p[i]; }
C++
복사
2.
Shap 클래스를 추상클래스로 만들고 다시 작성
#include <iostream> using namespace std; class Shape { protected: string name; int width, height; public: Shape(string n="", int w = 0, int h = 0) { name = n; width = w; height = h; } virtual double getArea() = 0; // 순수 가상함수 // 순수가상함수를 하나 이상 가지고 있는 클래스 -> 추상클래스 string getName() { return name; } }; class Oval : public Shape { public: Oval(string n, int w, int h) : Shape(n, w, h){;} virtual double getArea() { return 3.14 * width * height; } }; class Rect : public Shape { public: Rect(string n, int w, int h) : Shape(n, w, h){;} virtual double getArea() { return width * height; } }; class Triangular : public Shape { public: Triangular(string n, int w, int h) : Shape(n, w, h){;} virtual double getArea() { return (width * height) / 2; } }; int main() { Shape *p[3]; p[0] = new Oval("빈대떡", 10, 20); p[1] = new Rect("찰떡", 30, 40); p[2] = new Triangular("토스트", 30, 40); for (int i = 0; i < 3; i++) cout << p[i]->getName() << " 넓이는 " << p[i]->getArea() << endl; for (int i = 0; i < 3; i++) delete p[i]; Shape *s; s = new Rect("모양", 10, 20); cout << s->getName() << s->getArea() << endl; }
C++
복사