第十周 【项目4 - 类族的设计】

本文详细阐述了如何从Point类开始,逐步设计Circle和Cylinder类,实现圆的面积计算及圆柱体的表面积和体积计算。

 按以下的提示,由基类的设计和测试开始,逐渐地完成各个类的设计,求出圆格柱体的表面积、体积并输出并且完成要求的计算任务:

    (1)先建立一个Point(点)类,包含数据成员x,y(坐标点),实现需要的成员函数,并设计main函数完成测试;

    (2)以Point为基类,派生出一个Circle(圆)类,增加数据成员r(半径),以及求面积的成员函数area,实现其他需要的成员函数,设计main函数完成测试;

    (3)再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高),,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main函数完成测试。

     要求编写程序,设计出各类中“需要的成员函数”,包括构造函数、析构函数、修改数据成员和获取数据成员的公共接口、用于输出的重载运算符“<<”函数等。

参考答案如下:

#include<iostream>
using namespace std;
class point
{
protected:
    double x;
    double y;
public:
    point()
    {
        x=0;
        y=0;
    };
    ~point() {};
    void set_point();
    double get_x()
    {
        return x;
    }
    double get_y()
    {
        return y;
    }
};
class circle:public point
{
private:
    double r;
public:
    circle ()
    {
        r=0;
    };
    ~circle() {};
    void set_circle()
    {
        set_point();
        cin>>r;
    }
    double area();
    double get_r()
    {
        return r;
    }
};
class cylinder:public circle
{
private:
    double h;
public:
    cylinder()
    {
        h=0;
    };
    ~cylinder() {};
    void set_cylinder();
    double volume();
    friend ostream&operator<<(ostream&out,cylinder& c);

};
void point::set_point()
{
    char c1,c2,c3;
    cin>>c1>>x>>c2>>y>>c3;
    if(c1!='('||c2!=','||c3!=')')
        set_point();

}
double circle::area()
{
    return (3.14*r*r);
}
ostream&operator<<(ostream&out,cylinder& c)
{
    out<<"底的中心坐标为"<<"("<<c.get_x()<<","<<c.get_y()<<")";
    out<<"底面半径:"<<c.get_r()<<" "<<"高:"<<c.h<<" ";
    out<<"体积为"<<c.volume()<<endl;
    return out;
}
double cylinder::volume()
{
    return(area()*h);
}
void cylinder::set_cylinder()
{
    set_circle();
    cin>>h;
}

int main()
{
    cylinder C;
    cout<<"请输入所求圆柱体的底面中心坐标x,y,半径r,高h"<<endl;
    C.set_cylinder();
    cout<<C;
    return 0;
}

测试结果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值