• 考试复习


    声明抽象基类Shape,由它派生出3个子类:Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别求出以上三者的面积,三个图形的数据在定义对象时给定。再设计一个函数sumArea,求出三个图形面积之和。要求用基类指针数组,使它的每一个元素指向一个派生类对象。

    View Code
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    const double PI = acos(-1.0);
    
    class Shape {
    public:
        virtual double getArea() = 0;
    };
    
    class Circle : public Shape
    {
    private:
        double R;
    public:
        Circle(double r = 0) : R(r) {};
        double getArea() {
            return PI * R * R;
        }
    };
    
    class Rectangle : public Shape
    {
    private:
        double len,high;
    public:
        Rectangle(double l = 0, double h = 0) : len(l), high(h) {};
        double getArea() {
            return len * high;
        }
    };
    
    class Triangle : public Shape
    {
    private:
        double di,H;
    public:
        Triangle(double l = 0, double h = 0) : di(l), H(h) {};
        double getArea() {
            return di * H / 2;
        }
    };
    
    template <class T>
    void printArea(T sa) {
        cout << sa.getArea() << endl;
    }
    
    double sumArea(Shape** p,int x) {
        double sum = 0;
        for(int i = 0;i < x; i++) {
            sum += p[i]->getArea();
        }
        return sum;
    }
    
    int main() {
        Circle circle(12.6);
        Rectangle rectangle(4.5,8.4);
        Triangle triangle(4.5,8.4);
        cout<<"area of circle    =";   
        printArea(circle);           
        cout<<"area of rectangle =";   
        printArea(rectangle);      
        cout<<"area of triangle  =";
        printArea(triangle);
        Shape *pt[3] = {&circle,&rectangle,&triangle};
        cout << sumArea(pt,3) << endl;
        return 0;
    }
  • 相关阅读:
    论人力资源的危机及其对策(3)
    maven常见问题问答
    bigtall的敏捷日记(1)
    项目管理沙龙的第一次聚会纪要
    论人力资源的危机与对策(2)
    Crest的OO核心实现
    阿里巴巴图标库,助力微信小程序开发
    微信小程序漂亮的搜索框【样式】
    C# windows 服务看门狗
    微信小程序生命周期
  • 原文地址:https://www.cnblogs.com/gray035/p/3061458.html
Copyright © 2020-2023  润新知