设计3个类:Shape,Circle和Rectangle,并根据main()函数能输出样例内容 Shape类中包括函数double calculateArea() {return 0.0;} Circle类继承自Shape类,包括新数据成员double radius, 继承的double calculateArea()返回3.14159 * radius * radius Rectangle类继承自Shape类,包括新数据成员double width和double height 继承的double calculateArea()返回cwidth * height 此外,要求: 1. 为类设计能够初始化数据成员的构造函数, 2. 数据成员访问控制优先使用private其次protected再次public 3. 给定函数返回值不能修改
时间: 2023-07-16 13:12:12 浏览: 104
下面是代码实现:
```c++
#include<iostream>
using namespace std;
class Shape {
public:
virtual double calculateArea() const { return 0.0; }
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double calculateArea() const override {
return 3.14159 * radius * radius;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double calculateArea() const override {
return width * height;
}
};
int main() {
Shape* shape1 = new Circle(2.5);
Shape* shape2 = new Rectangle(3.0, 4.0);
cout << "The area of the circle is: " << shape1->calculateArea() << endl;
cout << "The area of the rectangle is: " << shape2->calculateArea() << endl;
delete shape1;
delete shape2;
return 0;
}
```
输出结果:
```
The area of the circle is: 19.6349
The area of the rectangle is: 12
```
阅读全文