• 考试复习


    声明抽象基类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;
    }
  • 相关阅读:
    Go内建容器篇
    Go基础语法篇
    【区块链】比特币Merkle树
    【区块链】Fabric 术语
    Apache旗下项目
    【区块链】Fabric0.6 与1.0
    rc.local不起作用
    命令行模式启动VMWare虚拟机
    vsftpd 530 Login incorrect 根本原因和解决方案
    Oracle的undotbs01.dbf文件太大(占用大量磁盘空间)处理方法 ORA-01654 空间不足 ORA-01653
  • 原文地址:https://www.cnblogs.com/gray035/p/3061458.html
Copyright © 2020-2023  润新知