编写一个程序计算出球、圆柱和圆锥的表面积和体积。 要求: (1)定义一个基类,至少含有一个数据成员半径,并设为保护成员; (2)定义基类的派生类球、圆柱、圆锥,都含有求表面积和体积的成员函数和输出函数; (3)编写主函数,求球、圆柱、圆锥的表面积和体积。
时间: 2023-05-29 16:03:32 浏览: 113
#include <iostream>
using namespace std;
class Shape {
protected:
double radius;
public:
Shape(double r) {
radius = r;
}
virtual double getArea() = 0;
virtual double getVolume() = 0;
virtual void print() = 0;
};
class Sphere : public Shape {
public:
Sphere(double r) : Shape(r) {}
double getArea() {
return 4 * 3.14 * radius * radius;
}
double getVolume() {
return 4.0 / 3.0 * 3.14 * radius * radius * radius;
}
void print() {
cout << "Sphere: " << endl;
cout << "Surface area: " << getArea() << endl;
cout << "Volume: " << getVolume() << endl;
}
};
class Cylinder : public Shape {
protected:
double height;
public:
Cylinder(double r, double h) : Shape(r) {
height = h;
}
double getArea() {
return 2 * 3.14 * radius * height + 2 * 3.14 * radius * radius;
}
double getVolume() {
return 3.14 * radius * radius * height;
}
void print() {
cout << "Cylinder: " << endl;
cout << "Surface area: " << getArea() << endl;
cout << "Volume: " << getVolume() << endl;
}
};
class Cone : public Shape {
protected:
double height;
public:
Cone(double r, double h) : Shape(r) {
height = h;
}
double getArea() {
return 3.14 * radius * (radius + sqrt(radius * radius + height * height));
}
double getVolume() {
return 1.0 / 3.0 * 3.14 * radius * radius * height;
}
void print() {
cout << "Cone: " << endl;
cout << "Surface area: " << getArea() << endl;
cout << "Volume: " << getVolume() << endl;
}
};
int main() {
Sphere s(5);
s.print();
Cylinder c(3, 10);
c.print();
Cone co(4, 7);
co.print();
return 0;
}