2-13-3 立体类族共有的抽象类

问题及代码:

#include <iostream>
using namespace std;

class CSolid
{
public:
    virtual double Area()=0;
    virtual double Volume()=0;
};

class CCube:public CSolid
{
public:
    CCube(double s=1):Side(s){};
    double Area();
    double Volume();
protected:
    double Side;
};

class CBall:public CSolid
{
public:
    CBall(double R=1):r(R){};
    double Area();
    double Volume();
protected:
    double r;

};

class CCylinder:public CSolid
{
public:
    CCylinder(double R=1,double h=1):r(R),height(h){};
    double Area();
    double Volume();
protected:
    double r,height;

};

double CCube::Area()
{
    return Side*Side*6;
}
double CCube::Volume()
{
    return Side*Side*Side;
}

double CBall::Area()
{
    return 4*3.14159*r*r;
}
double CBall::Volume()
{
    return (4*3.14159*r*r*r)/3;
}

double CCylinder::Area()
{
    return 3.14159*r*r*2+2*3.14159*r*height;
}
double CCylinder::Volume()
{
    return 3.14159*r*r*height;
}
int main()
{
    CSolid *p;

    CCube cc0,cc1(3);
    p=&cc0;
    cout<<"The area of cc0(Cube) is "<<p->Area()<<endl;
    cout<<"The volume of cc0(Cube) is "<<p->Volume()<<endl;
    p=&cc1;
    cout<<"The area of cc1(Cube) is "<<p->Area()<<endl;
    cout<<"The volume of cc1(Cube) is "<<p->Volume()<<endl;    //以上为用基类指针指向派生类CCube的对象
    cout<<endl;

    CBall cb0,cb1(2);
    p=&cb0;
    cout<<"The area of cb0(CBall) is "<<p->Area()<<endl;
    cout<<"The volume of cb0(CBall) is "<<p->Volume()<<endl;
    p=&cb1;
    cout<<"The area of cb1(CBall) is "<<p->Area()<<endl;
    cout<<"The volume of cb1(CBall) is "<<p->Volume()<<endl;    //以上为用基类指针指向派生类CBall的对象
    cout<<endl;

    CCylinder cy0,cy1(4,5);
    p=&cy0;
    cout<<"The area of cy0(CCylinder) is "<<p->Area()<<endl;
    cout<<"The volume of cy0(CCylinder) is "<<p->Volume()<<endl;
    p=&cy1;
    cout<<"The area of cy1(CCylinder) is "<<p->Area()<<endl;
    cout<<"The volume of cy1(CCylinder) is "<<p->Volume()<<endl;    //以上为用基类指针指向派生类CCylinder的对象

    return 0;
}


 

运行结果:

学习小结:

额,第一次在机房完成一周的项目啊,这周可以干点别的了。

这个项目完整的体验了一遍抽象类及其派生类的设计流程,挺顺利的

加油吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值