一道C++编程,书后的习题,请写代码
一道C++编程,书后的习题,请写代码事先编写一个程序,计算正方体、球体和圆柱体的表面积和体积。(提示:声明一个抽象基类container,派生类cube、sphere和c...
一道C++编程,书后的习题,请写代码事先编写一个程序,计算正方体、球体和圆柱体的表面积和体积。(提示:声明一个抽象基类 container,派生类cube、sphere和cylinder,基类中求表面积和体积的成员函数声明为纯虚函数。)
展开
1个回答
展开全部
C++代码:
#include "iostream"
using namespace std;
class container
{
public:
virtual double area() = 0; //计算表面积
virtual double volume() = 0; //计算体积
};
//正方体类
class cube : public container
{
protected:
double side; //边长
public:
cube(double side) : side(side){}
double area()
{
return side * side * 6;
}
double volume()
{
return side * side * side;
}
};
//球体类
class sphere : public container
{
protected:
double radius; //半径
public:
sphere(double radius) : radius(radius){}
double area()
{
return 4 * 3.14 * radius * radius;
}
double volume()
{
return 4 * 3.14 * radius * radius * radius / 3;
}
};
//圆柱体类
class cylinder : public container
{
protected:
double radius; //底面圆半径
double height; //高
public:
cylinder(double radius, double height) : radius(radius), height(height) {}
double area()
{
return 2 * 3.14 * radius * radius + 2 * 3.14 * radius * height;
}
double volume()
{
return 3.14 * radius * radius * height;
}
};
int main()
{
container *c;
c = new cube(2);
cout<<"正方体的表面积:"<<c->area()<<endl;
cout<<"正方体的体积:"<<c->volume()<<endl;
c = new sphere(2);
cout<<"球体的表面积:"<<c->area()<<endl;
cout<<"球体的体积:"<<c->volume()<<endl;
c = new cylinder(2, 3);
cout<<"圆柱体的表面积:"<<c->area()<<endl;
cout<<"圆柱体的体积:"<<c->volume()<<endl;
return 0;
}
运行测试:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询