给出下面的抽象基类container:
class container{
protected:
double radius;
public:
container(double radius1)
{
radius=radius1;
}
virtual double surface_area()=0;
virtual double volume()=0;
};
class container{
protected:
double radius;
public:
container(double radius1)
{
radius=radius1;
}
virtual double surface_area()=0;
virtual double volume()=0;
};
要求:建立3个继承container的派生类cube、sphere与cylinder,让每一个派生类都包含虚函数surface_area和volume(),分别用来计算正方体、球、圆柱体的表面积和体积。写出主程序,应用C++的多态性,分别计算边长为6.0的正方体、半径为5.0的球体和高为6.0的圆柱体的表面积和体积。
#include<iostream>
using namespace std;
class container{
protected:
double radius;
public:
container(double radius1)
{
radius=radius1;
}
virtual double surface_area()=0;
virtual double volume()=0;
};
class cube:public container //声明一个正方体派生类cube
{ public:
cube(double radius1):container(radius1)
{ }
double surface_area() //定义虚函数surface_area
{ return 6*radius*radius;
}
double volume() //定义虚函数volume
{ return radius*radius*radius;
}
};
class sphere:public container
{
public:
sphere(double radius1):container(radius1)
{}
double surface_area()
{
return 3.14*radius*radius*4;
}
double volume()
{
return 4/3*3.14*radius*radius;
}
};
class cylinder: public container //声明一个圆柱体派生类cylinder
{ double height;
public:
cylinder(double radius1,double height1):container(radius1)
{ height=height1;
}
double surface_area() //定义虚函数surface_area
{ return 2*3.1416*radius*(radius+height);
}
double volume() //定义虚函数volume
{ return 3.1416*radius*radius*height;
}
};
int main()
{
container *ptr;
cube obj1(5.0);
sphere obj2(5.0);
cylinder obj3(5.0,5.0);
ptr=&obj1; //指针ptr指向正方体类对象obj1
cout<<"这个正方体的表面积是:"<<ptr->surface_area()<<endl; //求正方体的表面积
cout<<"这个正方体的体积是:"<<ptr->volume()<<endl<<endl; //求正方体的的体积
ptr=&obj2; //指针ptr指向球体的类对象obj2
cout<<"这个球体表面积是:"<<ptr->surface_area()<<endl; //求球体的表面积
cout<<"这个球体的体积是:"<<ptr->volume()<<endl<<endl; //求球体的的体积
ptr=&obj3; //指针ptr指向圆柱体类的对象obj3
cout<<"这个圆柱体的表面积是:"<<ptr->surface_area()<<endl; //求圆柱体的表面积
cout<<"这个圆柱体的体积是:"<<ptr->volume()<<endl; //求圆柱体的的体积
system("pause");
return 0;
}
运行结果: