1、设计一个基类Shape,要求如下: (1)包含以下成员函数: . virtual void getInfo()= 9; m virtual void printInfo()=;" virtual double getArea()=; (2)从Shape派生出子类Circle,新增成员radius并实现基(3)在主函数中创建一个Shape指针数组,包含多个 Circle 循环遍历数组,通过指针调用成员函数,分别计算并输出每
时间: 2024-03-16 21:45:05 浏览: 60
以下是设计的代码实现:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual void getInfo() = 0;
virtual void printInfo() = 0;
virtual double getArea() = 0;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
void getInfo() {
cout << "This is a circle." << endl;
}
void printInfo() {
cout << "The radius of the circle is " << radius << "." << endl;
}
double getArea() {
return 3.1415926 * radius * radius;
}
private:
double radius;
};
int main() {
Circle c1(2.0), c2(3.0), c3(4.0);
Shape* shapes[3] = {&c1, &c2, &c3};
for (int i = 0; i < 3; i++) {
shapes[i]->getInfo();
shapes[i]->printInfo();
cout << "The area is " << shapes[i]->getArea() << "." << endl;
}
return 0;
}
```
在上面的代码中,我们定义了一个名为`Shape`的基类,它包含了三个纯虚函数`getInfo()`、`printInfo()`和`getArea()`,分别用于获取形状的信息、打印形状的信息和计算形状的面积。然后我们从`Shape`派生出了一个名为`Circle`的子类,它新增了一个成员变量`radius`,并实现了`getInfo()`、`printInfo()`和`getArea()`三个函数。在`main()`函数中,我们创建了三个`Circle`对象,并使用指针数组将它们存储起来。然后我们循环遍历数组,通过指针调用成员函数,分别计算并输出每个圆形的面积。
阅读全文
相关推荐



















