使用虚函数编写程序求球体和圆柱体的体积及表面积。
发布网友
发布时间:2024-05-28 19:16
我来回答
共1个回答
热心网友
时间:2024-06-12 06:41
#include<iostream>
#define PI 3.14159
class Circle
{
public:
float radius;
public:
Circle(float r)
{
radius = r;
};
virtual float area()
{
return PI * radius * radius;
};
virtual float volume()
{
return 0.0;
};
};
class Sphere : public Circle
{
public:
Sphere(float r)
{
radius = r;
};
virtual float area()
{
return 4 * PI * radius * radius;
};
virtual float volume()
{
return 4 * PI * radius * radius * radius / 3.0;
};
};
class Column : public Circle
{
public:
float height;
public:
Column(float r,float h)
{
radius = r;
height = h;
};
virtual float area()
{
return 2 * PI * radius * ( radius + height );
};
virtual float volume()
{
return PI * radius * radius * height;
};
};
int main()
{
Sphere s(20.0);
Column c(10.0,30.0);
cout << "s.area = "<<s.area()<<endl;
cout << "s.volume= "<<s.volume()<<endl;
cout << "c.area = "<<c.area()<<endl;
cout << "c.volume= "<<c.volume()<<endl;
return 0;
}