第十三週專案2——形狀類族的中的純虛擬函式
阿新 • • 發佈:2019-02-15
/* *Copyright (c) 2014,煙臺大學計算機學院 *All rights reserved. *檔名稱: test.cpp *作者: 郭棟 *完成日期:2015年 6月3日 *版本號:v1.0 *問題描述:寫一個程式,定義抽象基類Shape,由它派生出3個派生類,Circle(圓形)、Rectangle(矩形)、Triangle(三角形)。用如下的main()函式,求出定義的幾個幾何體的面積和。 */ #include<iostream> using namespace std; class Shape { public: virtual double area()=0; }; class Circle : public Shape { protected: double radius; public: Circle(double rad):radius(rad){} double area() { return (3.14*radius*radius); } }; class Rectangle : public Shape { protected: double longth,width; ; public: Rectangle(double lon,double wid):longth(lon),width(wid){} double area() { return (longth*width); } }; class Triangle : public Shape { protected: double longth,width; ; public: Triangle(double lon,double wid):longth(lon),width(wid){} double area() { return (longth*width/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; //輸出總面積 return 0; }
執行結果