立方體類組中的純虛函數類

來源:互聯網
上載者:User
/** Copyright (c) 2013, 煙台大學電腦學院* All rights reserved.* 檔案名稱:test.cpp* 作者:邱學偉* 完成日期:2013 年 6 月 2 日* 版本號碼:v1.0* 輸入描述:無* 問題描述:* 程式輸出:* 問題分析:* 演算法設計:略*//*設計一個抽象類別CSolid,含有兩個求表面積及體積的純虛函數。設計個衍生類別CCube、CBall、CCylinder,分別表示正方體、球體及圓柱體。在main()函數中,定義基類的指標p(CSolid *p;),利用p指標,輸出正方體、球體及圓柱體對象的表面積及體積。*/#include <iostream>using namespace std;class CSolid    //基類{    public:    virtual double area() const =0;    //純虛函數,求面積    virtual double volume() const =0;   //純虛函數,求體積};class CCube:public CSolid  //正方體{    public:    CCube(double w):width(w){}    virtual double area() const   //正方體的表面積    {        return 6*width*width;    }    virtual double volume() const  //正方體的體積    {        return width*width*width;    }    private:    double width;};class CBall:public CSolid  //球體{    public:    CBall(double r0):r(r0){}    virtual double area() const  //球體的表面積    {        return 4*3.14*r*r;    }    virtual double volume() const  //球體的體積    {        return (4*3.14*r*r*r)/3;    }    private:    double r;};class CCylinder:public CSolid{    public:    CCylinder(double r0,double h):r(r0),height(h){}    virtual double area() const    {        return 2*(3.14*r*r)+height*3.14*r*2;    }    virtual double volume() const    {        return height*3.14*r*r;    }    private:    double r,height;};int main(){    CSolid *p;    double s,v;    CCube c1(30);    p=&c1;    s=p->area();    v=p->volume();    cout<<"邊長為30的正方體表面積為:"<<s<<endl;    cout<<"邊長為30的正方體的體積為:"<<v<<endl;    CBall c2(5);    p=&c2;    s=p->area();    v=p->volume();    cout<<"半徑為5的球的表面積為:"<<s<<endl;    cout<<"半徑為5的球的體積為:"<<v<<endl;    CCylinder c3(5,4);    p=&c3;    s=p->area();    v=p->volume();    cout<<"半徑為5,高為4的圓柱的表面積為:"<<s<<endl;    cout<<"半徑為5,高為4的圓柱的體積為:"<<v<<endl;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.