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;
}


 

運行結果:

學習小結:

額,第一次在機房完成一週的項目啊,這周可以乾點別的了。

這個項目完整的體驗了一遍抽象類及其派生類的設計流程,挺順利的

加油吧

發佈了126 篇原創文章 · 獲贊 15 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章