图形
矩形、正方形、圆形
计算面积、面积输出
·面向对象设计,类?
·实现功能?
·运行时多态性测试?
1 #include <iostream>
2 using namespace std;
3
4 class Shape
5 {
6 protected:
7 double area;
8 public:
9 virtual double getArea() const = 0;
10 virtual void showArea()
11 {
12 cout << area << endl;
13 }
14 // friend ostream& operator << (ostream& out, const Shape& s);
15 };
16
17 ostream& operator << (ostream& out, const Shape& s)
18 {
19 out << s.getArea();
20 return out;
21 }
22
23 class Rectangle : public Shape
24 {
25 private:
26 double x;
27 double y;
28 public:
29 Rectangle(double i = 0.0, double j = 0.0) : x(i), y(j)
30 {
31 area = x * y;
32 }
33 virtual double getArea() const
34 {
35 return area;
36 }
37 };
38
39 class Square : public Shape
40 {
41 private:
42 double x;
43 public:
44 Square(double i = 0.0) : x(i)
45 {
46 area = x * x;
47 }
48 virtual double getArea() const
49 {
50 return area;
51 }
52 };
53
54 class Circle : public Shape
55 {
56 private:
57 double r;
58 static const double PI;
59 public:
60 Circle(double i = 0.0) : r(i)
61 {
62 area = PI * r * r;
63 }
64 virtual double getArea() const
65 {
66 return area;
67 }
68 };
69
70 const double Circle::PI = 3.1415926;
71
72 int main()
73 {
74 Shape* p;
75 p = new Rectangle(4, 5);
76 cout << p->getArea() << endl;
77 p->showArea();
78 delete p;
79 p = new Square(5);
80 cout << p->getArea() << endl;
81 p->showArea();
82 delete p;
83 p = new Circle(5);
84 cout << p->getArea() << endl;
85 p->showArea();
86 delete p;
87
88
89 Rectangle r(6, 7);
90 Square s(7);
91 Circle c(9);
92 cout << r << endl;
93 cout << s << endl;
94 cout << c << endl;
95
96 return 0;
97 }
posted on 2011-06-16 11:46
unixfy 阅读(194)
评论(0) 编辑 收藏 引用