用c++怎么编?

定义一个基类Shap,包含一个求面积的纯虚函数,由Shap类派生圆类、矩形类和三角形类,定义各自的数据成员、构造函数、求面积函数和求周长函数。编写主函数,定义各类对象及基... 定义一个基类Shap,包含一个求面积的纯虚函数,由Shap类派生圆类、矩形类和三角形类,定义各自的数据成员、构造函数、求面积函数和求周长函数。编写主函数,定义各类对象及基类指针,通过基类指针调用求面积和周长函数,计算各对象的面积和周长 展开
 我来答
FanyongYin
2013-05-02 · TA获得超过1054个赞
知道小有建树答主
回答量:1298
采纳率:100%
帮助的人:1011万
展开全部
#include <iostream>
#include <cmath>
using namespace std;
class Shape
{
    public:
        virtual double Area() = 0;
        virtual double Perimeter() = 0;
};
class Circle: public Shape
{
    public:
        Circle(double radius = 0.0)
        {
            this->radius = radius;
        }
        virtual double Area()
        {
            return Circle::PI * radius * radius;
        }
        virtual double Perimeter()
        {
            return 2 * Circle::PI * radius;
        }
    private:
        double radius;
        static const double PI;
};
const double Circle::PI = 3.1415926;
class Rectangle: public Shape
{
    public:
        Rectangle(double length = 0.0, double width = 0.0)
        {
            this->length = length;
            this->width  = width;
        }
        virtual double Area()
        {
            return length * width;
        }
        virtual double Perimeter()
        {
            return 2 * (length + width);
        }
    private:
        double length;
        double width;
};
class Triangle: public Shape
{
    public:
        Triangle(double a = 0.0, double b = 0.0, double c = 0.0)
        {
            bool isTriangle = false;
            isTriangle = (a + b > c) && (c + b > a) && (a + c > b);
            if (isTriangle)
            {
                this->a = a;
                this->b = b;
                this->c = c;
            }
            else
            {
                this->a = 0.0;
                this->b = 0.0;
                this->c = 0.0;
            }
        }
        virtual double Area()
        {
            double tmp = (a + b + c)/2;
            return sqrt(tmp * (tmp - a) * (tmp - b) * (tmp - c));
        }
        virtual double Perimeter()
        {
            return (a + b + c);
        }
    private:
        double a;
        double b;
        double c;
};
int main(void)
{
    Shape *pSh = NULL;
    Circle    c(3);
    Rectangle r(4, 5);
    Triangle  t(6, 7, 8);
    pSh = &c;
    cout << "Circle(3)'s Area="<<pSh->Area()<<", Perimeter="<<pSh->Perimeter()<<endl;
    pSh = &r;
    cout << "Rectangle(4, 5)'s Area="<<pSh->Area()<<", Perimeter="<<pSh->Perimeter()<<endl;
    pSh = &t;
    cout << "Triangle(6, 7, 8)'s Area="<<pSh->Area()<<", Perimeter="<<pSh->Perimeter()<<endl;
    return 0;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式