根据描述,我们需要设计两个类:Circle(圆)和Cylinder(圆柱体),它们都是从抽象基类Shape派生而来。以下是对应的代码示例:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void display() = 0; // 纯虚函数,在派生类中必须实现
virtual double area() = 0; // 纯虚函数,在派生类中必须实现
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
void display() {
cout << "圆的半径:" << radius << endl;
cout << "圆的面积:" << area() << endl;
}
double area() {
return 3.14 * radius * radius;
}
};
class Cylinder : public Shape {
private:
double radius;
double height;
public:
Cylinder(double r, double h) : radius(r), height(h) {}
void display() {
cout << "圆柱体的半径:" << radius << endl;
cout << "圆柱体的高度:" << height << endl;
cout << "圆柱体的表面积:" << area() << endl;
}
double area() {
return (2 * 3.14 * radius * height) + (2 * 3.14 * radius * radius);
}
};
int main() {
const unsigned NUM = 10;
Shape* a[NUM];
int i = 0, select;
double r, h;
while(i < NUM) {
cout << "输入图形类型(1:圆柱体 2:圆形): ";
cin >> select;
if (select < 1 || select > 2) {
cout << "输入出错,重新输入!" << endl;
continue;
}
if (select == 1) {
cout << "输入半径和高度:";
cin >> r >> h;
a[i] = new Cylinder(r, h);
} else {
cout << "输入半径:";
cin >> r;
a[i] = new Circle(r);
}
i++;
}
for (i = 0; i < NUM; i++) {
a[i]->display();
delete a[i];
}
return 0;
}
这样设计的Circle类和Cylinder类可以根据用户的选择创建对象,并调用对应的成员函数显示相关信息和计算面积。
内容由零声教学AI助手提供,问题来源于学员提问