多态与继承

多态与继承

主要重点记住

  1. 公有赋值兼容规则
  2. 虚函数与抽象类

从而实现动态联编

**我认为下面这个程序对本知识点回顾有较好的作用,顺便回顾一下之前讲过的函数指针指针与函数指针
**
至于知识点部分可能要在之后有时间的情况下再给大家补充了

下面程序对于这种不同对象之间的排序处理手法也是比较经典!

//几何图形面积输出排序
//by Gary
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
class Shape
{
public:
    virtual double calArea()=0;
    virtual void printArea()=0;
};

class CRectangle:public Shape
{
    double w,h;
public:
    CRectangle(double ww,double hh):w(ww),h(hh)
    {

    }
    double calArea();//不写virtual也是虚函数了
    void printArea();
};

class CCircle:public Shape
{
    double r;
public:
    CCircle(double rr):r(rr)
    {

    }
    double calArea();
    void printArea();
};

class CTriangle:public Shape
{
    double a,b,c;
public:
    CTriangle(double aa,double bb, double cc):a(aa),b(bb),c(cc)
    {

    }
    double calArea();
    void printArea();
};

double CRectangle::calArea()
{
    return w*h;
}
void CRectangle::printArea()
{
    cout<<calArea();
}

double CCircle::calArea()
{
    return 3.14*r*r;
}

void CCircle::printArea()
{
    cout<<calArea();
}

double CTriangle::calArea()
{
    double p=(a+b+c)/2;
    return sqrt(p*(p-a)*(p-b)*(p-c));
}

void CTriangle::printArea()
{
    cout<<calArea();
}

Shape *pShape[100];
int myCompare(const void *s1,const void *s2)
{
    Shape **p1=(Shape **)s1;
    Shape **p2=(Shape **)s2;
    double a1=(*p1)->calArea();
    double a2=(*p2)->calArea();
    if(a1<a2)
        return -1;
    else if(a1>a2)
        return 1;
    else
        return 0;
}

int main()
{
    int i, n;
    cout<<"Rule:'R'for Rectangle 'C'for Circle 'T'for Triangle"<<endl;
    cout<<"Please input the number:";
    cin>>n;
    for(i=0;i<n;++i)
    {
        char c;
        cout<<"intput the shape:";
        cin>>c;
        switch(c)
        {
        case 'R':
            double w,h;
            cout<<"input width and height:";
            cin>>w>>h;
            pShape[i]=new CRectangle(w,h);
            break;
        case 'T'://这里我不对输入正确与否进行处理了,大家可以自行修改一下
            double a,b,c;
            cout<<"input the edge length:";
            cin>>a>>b>>c;
            pShape[i]=new CTriangle(a,b,c);
            break;
        case 'C':
            double r;
            cout<<"input the radius:";
            cin>>r;
            pShape[i]=new CCircle(r);
            break;
        }
    }
    qsort(pShape,n,sizeof(Shape*),myCompare);
    for(int i=0;i<n;i++)
    {
        pShape[i]->printArea();
        cout<<" ";
        delete pShape[i];
    }
        return 0;
}

学会程序和算法,走遍天下都不怕
在这里插入图片描述
维也纳金色大厅

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值