第十三周實驗報告三

來源:互聯網
上載者:User
<span style="font-size:18px;">//【任務】寫一個程式,定義抽象基類Shape,由它派生出個衍生類別,Circle(圓形)、Rectangle(矩形)、Triangle(三角形)。用如下的mian()函數,求出定義的幾個幾何體的面積和。</span>  

來源程式及運行結果

 

<span style="font-size:18px;">#include<iostream>#define pi 3.14using namespace std;class Shape{public:virtual double Area() = 0;};class Circle: public Shape{private:double radius;public:Circle(double r):radius(r){};double Area();};double Circle::Area(){return (pi * radius * radius);}class Rectangle: public Shape{private:double length;double width;public:Rectangle(double l,double w):length(l),width(w){};double Area();};double Rectangle::Area(){return (length * width);}class Triangle:public Shape{private:double base;double height;public:Triangle(double b,double h):base(b),height(h){};double Area();};double Triangle::Area(){return ((base * height)/2);}int main(){Circle c1(12.6),c2(4.9);    //建立Circle類對象c1,c2,參數為圓半徑Rectangle r1(4.5,8.4),r2(5.0,2.5);       //建立Rectangle類對象r1,r2,參數為矩形長、寬Triangle t1(4.5,8.4),t2(3.4,2.8);    //建立Triangle類對象t1,t2,參數為三角形底邊長與高Shape *pt[6]={&c1,&c2,&r1,&r2,&t1,&t2}; //定義基類指標數組pt,各元素指向一個衍生類別對象double areas=0.0;      //areas為總面積for(int i=0; i<6; i++){areas=areas+pt[i]->Area();}cout<<"totol of all areas="<<areas<<endl;   //輸出總面積system("pause");return 0;}運行結果:totol of all areas=647.858請按任意鍵繼續. . .</span>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.