7、形狀(一) 編寫C++程序完成以下功能: (1) 聲明一個基類Shape(形狀),其中包含一個方法來計算面積; (2) 從Shape派生兩個類矩形和圓形; (3) 從矩形派生正方形; (4) 分別實現(xiàn)派生類構(gòu)造函數(shù)、析構(gòu)函數(shù)和其他方法; (5) 創(chuàng)建派生類的對象,觀察構(gòu)造函數(shù)、析構(gòu)函數(shù)調(diào)用次序; (6) 不同對象計算面積。 #include<iostream> #define PI 3.1415 using namespace std; class Shape { public: Shape() {cout<<"調(diào)用構(gòu)造函數(shù)Shape"<<endl;} ~Shape() {cout<<"調(diào)用析構(gòu)函數(shù)Shape"<<endl;} double Girth() {} double Area() {} }; class Rectangle: public Shape { private: double len; double wide; public: Rectangle(double l=0,double w=0) {len=l; wide=w; cout<<"調(diào)用構(gòu)造函數(shù)Rectangle"<<endl;} void SetRectangle(double l=0,double w=0) {len=l; wide=w;} ~Rectangle(){cout<<"調(diào)用析構(gòu)函數(shù)Rectangle"<<endl;} double Girth() {return (len+wide)*2;} double Area() {return len*wide;} }; class Circle:public Shape { private: double r; public: Circle(double radius=0) {r=radius; cout<<"調(diào)用構(gòu)造函數(shù)Circle"<<endl;} void SetCircle(double radius=0) {r=radius;} ~Circle(){cout<<"調(diào)用析構(gòu)函數(shù)Circle"<<endl;} double Girth() {return 2*PI*r;} double Area() {return PI*r*r;} }; class Square:public Rectangle { public: Square(double x=0) {Rectangle(x,x); cout<<"調(diào)用構(gòu)造函數(shù)Square"<<endl;} void SetSquare(double x=0) {SetRectangle(x,x);} ~Square(){cout<<"調(diào)用析構(gòu)函數(shù)Square"<<endl;} }; int main() { Rectangle b; Circle c; Square d; double x,y,m,n; cout<<endl<<"請輸入矩形長和寬(用空格隔開):"<<endl; cin>>x>>y; b.SetRectangle(x,y); cout<<"矩形周長為:"<<b.Girth()<<endl; cout<<"矩形面積為:"<<b.Area()<<endl; cout<<endl<<"請輸入圓形的半徑:"<<endl; cin>>m; c.SetCircle(m); cout<<"圓形周長為:"<<c.Girth()<<endl; cout<<"圓形面積為:"<<c.Area()<<endl; cout<<endl<<"請輸入正方形的邊長:"<<endl; cin>>n; d.SetSquare(n); cout<<"正方形周長為:"<<d.Girth()<<endl; cout<<"圓形面積為:"<<d.Area()<<endl; system("pause"); cout<<endl; return 0; }
![]() |
|