第十三周任務三(抽象基類的應用)

來源:互聯網
上載者:User

【任務3】寫一個程式,定義抽象基類Shape,由它派生出3 個衍生類別,Circle(圓形)、Rectangle(矩形)、
Triangle(三角形)。用如下的mian()函數,求出定義的幾個幾何體的面積和。
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;
}


來源程式:

#include<iostream>using namespace std;class Shape{public:virtual double area() const = 0;};class Circle:public Shape{public:virtual double area() const {return 3.14159 * R * R;}Circle(double r){R = r;}private:double R;};class Rectangle:public Shape{public:virtual double area() const {return Long * Wide;}Rectangle(double l,double w){Long = l; Wide = w;}private:double Long;double Wide;};class Triangle:public Shape{public:virtual double area() const {return 0.5 * side * high;}Triangle(double s,double h){side = s; high = h;}private:double side;double high;};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= 648.148
請按任意鍵繼續. . .


經驗積累:

抽象積累就像大將軍,扛槍打仗的事交給士兵們,留給自己的只有作戰架構。。。

聯繫我們

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