zoukankan      html  css  js  c++  java
  • 多态性的一个典型的例子

     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:
    x="<<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:
    "<<c;
    70     Point &pRef=c;
    71     cout <<"pRef:"<<pRef;
    72     return 0;
    73 }
  • 相关阅读:
    Oracle FGA审计记录的清理步骤
    UVa11488-Hyper Prefix Sets(trie树)
    配置Log4j(非常具体)
    poj1190生日蛋糕
    zju1610Count the Colors
    【例9.3】求最长不下降序列
    P1364 医院设置
    P1629 邮递员送信
    P1476 休息中的小呆
    P1330 封锁阳光大学
  • 原文地址:https://www.cnblogs.com/borter/p/9405500.html
Copyright © 2011-2022 走看看