计算几种不同的三维图形的表面积和体积。这里 定义一个抽象类CShape,将其成员函数显示基本图形信息函数DispAttr0、计算表面积函数SArea0和计算体积函数volumeQ定义为纯虛函数。根据此抽象类 派生出球体、正方体、 •长方体和圆柱体,并分别重新 实现基类中的纯虛函数来显示输出计算结果。c++
时间: 2024-03-10 16:48:04 浏览: 86
好的,这是根据您的要求修改后的代码:
```C++
#include <iostream>
using namespace std;
const double PI = 3.14159265358979323846;
class CShape {
public:
virtual void DispAttr0() = 0;
virtual double SArea0() = 0;
virtual double volumeQ() = 0;
};
class CCube : public CShape {
public:
CCube(double a) : m_a(a) {}
void DispAttr0() { cout << "正方体:边长 = " << m_a << endl; }
double SArea0() { return 6 * m_a * m_a; }
double volumeQ() { return m_a * m_a * m_a; }
private:
double m_a;
};
class CSphere : public CShape {
public:
CSphere(double r) : m_r(r) {}
void DispAttr0() { cout << "球体:半径 = " << m_r << endl; }
double SArea0() { return 4 * PI * m_r * m_r; }
double volumeQ() { return 4.0 / 3.0 * PI * m_r * m_r * m_r; }
private:
double m_r;
};
class CRectangle : public CShape {
public:
CRectangle(double a, double b, double c) : m_a(a), m_b(b), m_c(c) {}
void DispAttr0() { cout << "长方体:长 = " << m_a << ", 宽 = " << m_b << ", 高 = " << m_c << endl; }
double SArea0() { return 2 * (m_a * m_b + m_b * m_c + m_c * m_a); }
double volumeQ() { return m_a * m_b * m_c; }
private:
double m_a;
double m_b;
double m_c;
};
class CCylinder : public CShape {
public:
CCylinder(double r, double h) : m_r(r), m_h(h) {}
void DispAttr0() { cout << "圆柱体:底面半径 = " << m_r << ", 高 = " << m_h << endl; }
double SArea0() { return 2 * PI * m_r * m_h + 2 * PI * m_r * m_r; }
double volumeQ() { return PI * m_r * m_r * m_h; }
private:
double m_r;
double m_h;
};
int main() {
CCube cube(2);
cube.DispAttr0();
cout << "表面积 = " << cube.SArea0() << endl;
cout << "体积 = " << cube.volumeQ() << endl;
CSphere sphere(3);
sphere.DispAttr0();
cout << "表面积 = " << sphere.SArea0() << endl;
cout << "体积 = " << sphere.volumeQ() << endl;
CRectangle rectangle(2, 3, 4);
rectangle.DispAttr0();
cout << "表面积 = " << rectangle.SArea0() << endl;
cout << "体积 = " << rectangle.volumeQ() << endl;
CCylinder cylinder(2, 4);
cylinder.DispAttr0();
cout << "表面积 = " << cylinder.SArea0() << endl;
cout << "体积 = " << cylinder.volumeQ() << endl;
return 0;
}
```
这里重新定义了抽象类CShape,并分别派生出了正方体、球体、长方体和圆柱体这四个类。这些类实现了基本图形信息、表面积和体积的计算方法。在主函数中,我们分别创建了一个正方体、球体、长方体和圆柱体的对象,并调用它们的成员函数来显示基本图形信息、计算表面积和体积,并输出计算结果。
阅读全文