用c++ 定义一个Shape类,记录任意形状的位置,在Shape类的基础上派生出一个Rectangle 类和一个Circle 类,在Rectangle 类的基础上派生出一个Square 类,必须保证每个类都有计算面积和周长的功能
时间: 2024-05-03 13:19:43 浏览: 189
设计一个Shape接口和它的两个实现类Square和Circle,要求如下
以下是一个可能的实现,其中Shape类是抽象基类,派生类必须实现纯虚函数`area()`和`perimeter()`来计算面积和周长:
```c++
#include <iostream>
class Shape {
public:
Shape(double x, double y) : x_{x}, y_{y} {}
virtual ~Shape() = default;
virtual double area() const = 0;
virtual double perimeter() const = 0;
double x() const { return x_; }
double y() const { return y_; }
private:
double x_;
double y_;
};
class Rectangle : public Shape {
public:
Rectangle(double x, double y, double w, double h)
: Shape(x, y), width_{w}, height_{h} {}
double area() const override { return width_ * height_; }
double perimeter() const override { return 2 * (width_ + height_); }
double width() const { return width_; }
double height() const { return height_; }
private:
double width_;
double height_;
};
class Circle : public Shape {
public:
Circle(double x, double y, double r) : Shape(x, y), radius_{r} {}
double area() const override { return 3.1415926 * radius_ * radius_; }
double perimeter() const override { return 2 * 3.1415926 * radius_; }
double radius() const { return radius_; }
private:
double radius_;
};
class Square : public Rectangle {
public:
Square(double x, double y, double side)
: Rectangle(x, y, side, side), side_{side} {}
double side() const { return side_; }
private:
double side_;
};
int main() {
Shape* shapes[] = {
new Rectangle(0, 0, 3, 4),
new Circle(0, 0, 2),
new Square(0, 0, 5),
};
for (auto s : shapes) {
std::cout << "x = " << s->x() << ", y = " << s->y() << std::endl;
std::cout << "area = " << s->area() << ", perimeter = " << s->perimeter() << std::endl;
std::cout << std::endl;
}
for (auto s : shapes) {
delete s;
}
return 0;
}
```
在此示例中,Shape类是抽象基类,因为它包含了纯虚函数。Rectangle和Circle类从Shape类继承,并重写了`area()`和`perimeter()`函数,以便计算它们自己的面积和周长。Square类从Rectangle类继承,但只需要提供一个边长来创建一个正方形。在主函数中,我们创建了一个Shape指针数组,并用不同的形状初始化它。然后,我们循环遍历数组,并输出每个形状的位置、面积和周长。最后,我们必须删除每个形状的内存,以避免内存泄漏。
阅读全文