#include<iostream>using namespace std;class Shape{public:virtual double printArea()const{return 0.0;}virtual double printVol()const{return 0.0;}};class Circle:public Shape{public:Circle(double r):rad(r){}double printArea(){return 3.14*rad*rad;}private:double rad;};class Rect:public Shape{public:Rect(double l,double w):len(l),wid(w){}double printArea(){return len*wid;}private:double len,wid;};class Tri:public Shape{public:Tri(double l,double h):len(l),hei(h){}double printArea(){return 0.5*len*hei;}private:double len,hei;};class Cy:public Circle{public:Cy(double r,double h):rad(r),hei(h){}double printArea(){return (2*3.14*rad*rad+2*3.14*rad*hei);}double printVol(){return 3.14*rad*rad*hei;}private:double rad,hei;};class Rec:public Rect{public:Rec(double l,double k,double h):len(l),kuan(k),hei(h){}double printArea(){return (2*len*kuan+2*len*hei+2*hei*kuan);}double printVol(){return len*kuan*hei;}private:double len,kuan,hei;};int main(){Circle a(10);Rect b(10,20);Tri c(10,20);Cy d(10,20);Rec e(10,10,10);Shape * p;p=&a;cout<<p->printArea()<<endl;p=&b;cout<<p->printArea()<<endl;p=&c;cout<<p->printArea()<<endl;p=&d;cout<<p->printArea()<<endl;cout<<p->printVol()<<endl;p=&e;cout<<p->printArea()<<endl;cout<<p->printVol()<<endl;return 0;}
2 回答

萬千封印
TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
改兩處,基類的構(gòu)造函數(shù)沒有默認(rèn)的,要么加上默認(rèn)的,要么顯式調(diào)用帶參版本的基類構(gòu)造。
另外,你可能看不到你想要的結(jié)果,所有子類的printArea函數(shù)并沒有重寫父類Sharp的printArea函數(shù),所以,需要將每個(gè)子類的printArea函數(shù)帶上const修飾。
在C++中,函數(shù)重寫,要滿足四個(gè)等同條件:
返回值類型
函數(shù)名稱
參數(shù)列表
函數(shù)屬性(常函數(shù)/非常函數(shù))
當(dāng)然還有最重要的一點(diǎn)就是,父類的函數(shù)得是虛函數(shù),也就是前邊得有virtual關(guān)鍵字修飾。
- 2 回答
- 0 關(guān)注
- 282 瀏覽
添加回答
舉報(bào)
0/150
提交
取消