多态性的一个典型的例子

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 class Point
 6 {
 7     public:
 8         Point(float x=0,float y=0);
 9         void setPoint(float,float);
10         float getX()const{return x;}
11         float getY()const{return y;}
12         friend ostream&operator<<(ostream&,const Point&);
13     protected:
14         float x,y;
15 };
16 
17 Point::Point(float a,float b)
18 {
19     x=a;
20     y=b;
21 }
22 
23 void Point::setPoint(float a,float b)
24 {
25     x=a;
26     y=b;
27 }
28 ostream&operator<<(ostream&output,const Point &p)
29 {
30     output<<"["<<p.x<<","<<p.y<<"]"<<endl;
31     return output;
32 }
33 class Circle:public Point
34 {
35     public:
36         Circle(float x=0,float y=0,float r=0);
37         void setRadius(float);
38         float getRadius()const;
39         float area()const;
40         friend ostream &operator<<(ostream&,const Circle&);
41     private:
42         float radius;
43 };
44 
45 Circle::Circle(float a,float b,float r):Point(a,b),radius(r){
46     
47 }
48 void Circle::setRadius(float r)
49 {
50     radius=r;
51 }
52 float Circle::getRadius()const{return radius;}
53 
54 float Circle::area()const
55 {
56     return 3.14159*radius*radius;
57 }
58 
59 ostream&operator<<(ostream &output,const Circle &c)
60 {
61     output<<"Center=["<<c.x<<","<<c.y<<"],r="<<c.radius<<",area="<<c.area()<<endl;
62     return output;
63 }
64 int main(int argc, char** argv) {
65     Circle c(3.5,6.4,5.2);
66     cout<<"original circle:\nx="<<c.getX()<<",y="<<c.getY()<<",r="<<c.getRadius()<<",area="<<c.area()<<endl;
67     c.setRadius(7.5);
68     c.setPoint(5,5);
69     cout<<"new circle:\n"<<c;
70     Point &pRef=c;
71     cout <<"pRef:"<<pRef;
72     return 0;
73 }

 

转载于:https://www.cnblogs.com/borter/p/9405500.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值