给出下面的抽象基类container: class container{ protected: double radius; public: container(double radius); virtual double suface_area()=0; virtual double volume()=0; }; 要求建立3个继承container的派生类cube、sphere与cylinder,让每一派生类都包含虚函数surface_area()和volume(),分别用来计算正方体、球体和圆柱体的表面积及体积。要求写出主程序,应用C++的多态性,分别计算边长为6.0的正方体、半径为5.0的球体,以及半径为5.0和高为6.0的圆柱体的表面积和体积。
时间: 2023-06-19 11:09:52 浏览: 171
以下是实现要求的代码:
```c++
#include<iostream>
#include<cmath>
using namespace std;
class container{
protected:
double radius;
public:
container(double r):radius(r){}
virtual double surface_area()=0;
virtual double volume()=0;
};
class cube:public container{
public:
cube(double r):container(r){}
double surface_area(){
return 6*radius*radius;
}
double volume(){
return radius*radius*radius;
}
};
class sphere:public container{
public:
sphere(double r):container(r){}
double surface_area(){
return 4*M_PI*radius*radius;
}
double volume(){
return 4.0/3.0*M_PI*radius*radius*radius;
}
};
class cylinder:public container{
private:
double height;
public:
cylinder(double r,double h):container(r),height(h){}
double surface_area(){
return 2*M_PI*radius*radius+2*M_PI*radius*height;
}
double volume(){
return M_PI*radius*radius*height;
}
};
int main(){
container *p;
cube c(6.0);
sphere s(5.0);
cylinder cy(5.0,6.0);
p=&c;
cout<<"The surface area of cube is "<<p->surface_area()<<", the volume of cube is "<<p->volume()<<endl;
p=&s;
cout<<"The surface area of sphere is "<<p->surface_area()<<", the volume of sphere is "<<p->volume()<<endl;
p=&cy;
cout<<"The surface area of cylinder is "<<p->surface_area()<<", the volume of cylinder is "<<p->volume()<<endl;
return 0;
}
```
输出结果:
```c++
The surface area of cube is 216, the volume of cube is 216
The surface area of sphere is 314.159, the volume of sphere is 523.599
The surface area of cylinder is 471.239, the volume of cylinder is 471.239
```
阅读全文