第十四周專案四立體類族共有的抽象類
阿新 • • 發佈:2019-01-11
/* * 程式的版權和版本宣告部分 * Copyright (c)2014, 煙臺大學計算機學院學生 * All rightsreserved. * 檔名稱: array.cpp * 作 者: 紀麗娜 * 完成日期: 2014 年 05 月 27 日 * 版本號: v1.0 * 問題描述: 設計一個抽象類CSolid,含有用於求表面積及體積的兩個純虛擬函式。 設計派生類CCube、CBall、CCylinder,分別表示正方體、球體及圓柱體。在main()函式中, 定義CSolid *p;(p是指向基類的指標,且這個基類是個抽象類)。要求利用這個p指標, 能夠求出正方體、球體及圓柱體物件的表面積及體積。 */ #include <iostream> #include <Cmath> #define PI 3.14159 using namespace std; class CSolid { public: virtual double area() const =0; virtual double volume() const =0; }; class CCube: public CSolid //正方體 { private: double a; public: CCube(double x):a(x) {} double area() const { return (6*a*a); } double volume() const { return (a*a*a); } ~CCube() {} }; class CBall : public CSolid //球體 { private: double r; public: CBall(double x):r(x) {} double area()const { return (4*PI*r*r); } double volume()const { double v=r*r*r; return ((4*PI*v)/3); } ~CBall(){} }; class CCylinder :public CSolid //圓柱體 { private: double r,h; public: CCylinder(double x,double y):r(x),h(y){} double area()const { double c=2*PI*r*h; double cy=4*PI*r; return (c+cy); } double volume()const { return (h*PI*r*r); } ~CCylinder() {} }; int main() { CSolid *p; CCube c1(5.0); p=&c1; cout<<"正方體的體積為:"<<p->area()<<endl; cout<<"正體的表面積為:"<<p->volume()<<endl; CBall c2(4.0); p=&c2; cout<<"球體的體積為:"<<p->area()<<endl; cout<<"球體的表面積為:"<<p->volume()<<endl; CCylinder c3(4.0,5.0); p=&c3; cout<<"圓柱體的體積為:"<<p->area()<<endl; cout<<"圓柱體的表面積為:"<<p->volume()<<endl; return 0; }
心得:千辛萬苦啊。。。。
基類後有const的後面派生類裡面都要加!!!!
p->。。。
*p.。。。