zoukankan      html  css  js  c++  java
  • C++实训(3.3)

    抽象类-编写一个程序,用于计算正方形、矩形、直角三角形和圆的面积之和。

    源程序:

    //纯虚函数与抽象类
    #include <iostream>
    using namespace std;
    class shape //shape类中有纯虚函数,所以shape是抽象类,抽象类定义的对象也是抽象的,只能用指针对象,不能用普通对象,更不能用普通对象的实例化
    { //如在主函数中用 shape A(5)就是错误的,只能用 shape *pa;
    public:
    virtual double area() = 0; //抽象类至少有一个虚函数,而且至少有一个是纯虚函数。这个函数就是一个纯虚函数
    virtual double area1() //这是一个虚函数,因为area1()的返回类型是double,所以必须要定义return 0;
    {
    return 0;
    }
    };

    class square :public shape
    {
    protected:
    double H;
    public:
    square(double i)
    {
    H = i;
    }
    double area()
    {
    return H * H;
    }
    };

    class circle :public square
    {
    public:
    circle(double r) :square(r)
    {}
    double area()
    {
    return H * H * 3.14159;
    }
    };
    class triangle :public square
    {
    protected:
    double W;
    public:
    triangle(double h, double w) :square(h)
    {
    W = w;
    }
    double area()
    {
    return H * W * 0.5;
    }
    };

    class rectangle :public triangle
    {
    public:
    rectangle(double h, double w) :triangle(h, w)
    {}
    double area()
    {
    return H * W;
    }
    };

    double total(shape* s[], int n)
    {
    double sum = 0.0;
    for (int i = 0; i < n; i++)
    sum = sum + s[i]->area();
    return sum;
    }
    int main()
    {
    // shape A(6); //不能给抽象的对象实例化
    shape* s[5];
    s[0] = new square(4);
    s[1] = new triangle(3, 6);
    s[2] = new rectangle(3, 6);
    s[3] = new square(6);
    s[4] = new circle(10);
    for (int i = 0; i < 5; i++)
    {
    cout << "s[" << i << "]=" << s[i]->area() << endl;
    }
    double sum = total(s, 5);
    cout << "The total area is:" << sum << endl;
    system("pause");
    return 1;
    }

    运行结果:

  • 相关阅读:
    Load Balancing 折半枚举大法好啊
    Big String 块状数组(或者说平方分割)
    K-th Number 线段树(归并树)+二分查找
    D. Powerful array 莫队算法或者说块状数组 其实都是有点优化的暴力
    CSU OJ PID=1514: Packs 超大背包问题,折半枚举+二分查找。
    运行时Runtime的API
    UIView的API
    UIControl的API
    UIScrollView的API
    使用KVO键值监听
  • 原文地址:https://www.cnblogs.com/duanqibo/p/13149930.html
Copyright © 2011-2022 走看看