第十三周上机实践——项目4-立体类族共有的抽象类

/*
 *Copyright (c)2016,烟台大学计算机与控制工程学院
 *All rights reserved.
 *文件名称:main.cpp,CSolid.h,CSolid.cpp
 *作    者:郭永恒
 *完成日期:2016年5月28日
 *版 本 号:v1.0
 *
 *问题描述:设计一个抽象类CSolid,含有用于求表面积和求体积的两个纯虚函数
 *设计派生类CCube,CBall,CCylinder
 */

CSolid.h

#ifndef CSOLID_H_INCLUDED
#define CSOLID_H_INCLUDED

class CSolid
{
public:
    virtual double surfaceArea() = 0;
    virtual double volume() = 0;
};

class CCube:public CSolid
{
public:
    CCube(double l, double w, double h):length(l),width(w),height(h){}
    double surfaceArea();
    double volume();
private:
    double length;
    double width;
    double height;
};

class CBall:public CSolid
{
public:
    CBall(double r):radius(r){}
    double surfaceArea();
    double volume();
private:
    static constexpr double PI = 3.1415926;
    double radius;
};

class CCylinder:public CSolid
{
    public:
    CCylinder(double r, double h):radius(r),height(h){}
    double surfaceArea();
    double volume();
private:
    static constexpr double PI = 3.1415926;
    double radius;
    double height;
};

#endif // CSOLID_H_INCLUDED
CSolid.cpp

#include "CSolid.h"

double CCube::surfaceArea()
{
    return (length*width + length*height + width*height)*2;
}

double CCube::volume()
{
    return length * height * width;
}

double CBall::surfaceArea()
{
    return 4 * PI * radius * radius;
}

double CBall::volume()
{
    return (4*PI*radius*radius*radius) / 3;
}

double CCylinder::surfaceArea()
{
    return 2*PI*radius*height + PI*radius*radius*2;
}

double CCylinder::volume()
{
    return PI*radius*radius*height;
}

main.cpp

#include <iostream>
#include "CSolid.h"
using namespace std;

int main()
{
    CSolid *p = nullptr;
    CCube cube(1,2,3);
    p = &cube;
    cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;
    CBall ball(2);
    p = &ball;
    cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;
    CCylinder cylinder(2,2);
    p = &cylinder;
    cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;
    return 0;
}

运行结果:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值