# Полиморфизм. Простой пример

Jan 24th, 2014
167
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #define _USE_MATH_DEFINES
2.
3. #include <iostream>
4.
5. using namespace std;
6.
7. class shape {
8. public:
9.     virtual double get_area()const = 0;
10.     virtual double get_perimeter()const = 0;
11.     virtual ~shape() { }
12. };
13.
14. class circle : public shape {
15. public:
16.     circle(double);
17.     virtual double get_area()const;
18.     virtual double get_perimeter()const;
19. private:
20.     circle() { }
22. };
23.
24. class rectangle : public shape {
25. public:
26.     rectangle(double, double);
27.     virtual double get_area()const;
28.     virtual double get_perimeter()const;
29. private:
30.     rectangle() { }
31.     double width;
32.     double height;
33. };
34.
35. class triangle : public shape {
36. public:
37.     triangle(double, double, double);
38.     virtual double get_area()const;
39.     virtual double get_perimeter()const;
40. private:
41.     triangle() { }
42.     double a;
43.     double b;
44.     double c;
45. };
46.
47. int main() {
48.     const shape * ptr = NULL;
49.
50.     const circle    c(3.25);
51.     const rectangle r(7.12, 4.3);
52.     const triangle  t(2.65, 3.15, 2.88);
53.
54.     ptr = &c;
55.     cout << " Sc = " << ptr->get_area() << "\tPc = " << ptr->get_perimeter() << endl;
56.     ptr = &r;
57.     cout << " Sr = " << ptr->get_area() << "\tPr = " << ptr->get_perimeter() << endl;
58.     ptr = &t;
59.     cout << " St = " << ptr->get_area() << "\tPt = " << ptr->get_perimeter() << endl;
60.     cout << endl;
61.
62.     const size_t size = 3;
63.     const shape * descendants[size];
64.     descendants[0] = &c;
65.     descendants[1] = &r;
66.     descendants[2] = &t;
67.
68.     for (rsize_t n = 0; n < size; n++)
69.         cout << " S = " << descendants[n]->get_area() << "\tP = " << descendants[n]->get_perimeter() << endl;
70.
71.     cin.get();
72.     return 0;
73. }
74.
75. circle::circle(double _r) : radius(_r) { }
76. double circle::get_perimeter()const { return 2 * M_PI * radius; }
78.
79. rectangle::rectangle(double _w, double _h) : width(_w), height(_h) { }
80. double rectangle::get_perimeter()const { return (width + height) * 2; }
81. double rectangle::get_area()const { return width * height; }
82.
83. triangle::triangle(double _a, double _b, double _c) : a(_a), b(_b), c(_c) { }
84. double triangle::get_perimeter()const { return a + b + c; }
85. double triangle::get_area()const {
86.     double p = get_perimeter() / 2;
87.     return sqrt(p * (p - a) * (p - b) * (p - c));
88. }