定义一个Point类,派生出Rectangle和Circle类,计算个派生类对象的面积Area()。 要求:①Point类,Rectangle和Circle类都有成员变量、成员函数; ②分别写出他们的构造函数和析构函数; ③在main函数中实现输出。 ④力争做到数据输入输出的直观性。
时间: 2024-02-21 08:02:12 浏览: 74
以下是一个可能的实现,其中Point类包含了x和y坐标,Rectangle类包含了左上角和右下角两个点的坐标,Circle类包含了圆心和半径:
```
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
Point(double x = 0, double y = 0);
~Point();
double getX() const;
double getY() const;
void setX(double x);
void setY(double y);
private:
double m_x;
double m_y;
};
class Rectangle : public Point {
public:
Rectangle(double x1 = 0, double y1 = 0, double x2 = 0, double y2 = 0);
~Rectangle();
double getWidth() const;
double getHeight() const;
double getArea() const;
private:
double m_width;
double m_height;
};
class Circle : public Point {
public:
Circle(double x = 0, double y = 0, double r = 0);
~Circle();
double getRadius() const;
double getArea() const;
private:
double m_radius;
};
Point::Point(double x, double y) : m_x(x), m_y(y) {
cout << "Constructing Point (" << m_x << ", " << m_y << ")" << endl;
}
Point::~Point() {
cout << "Destructing Point (" << m_x << ", " << m_y << ")" << endl;
}
double Point::getX() const {
return m_x;
}
double Point::getY() const {
return m_y;
}
void Point::setX(double x) {
m_x = x;
}
void Point::setY(double y) {
m_y = y;
}
Rectangle::Rectangle(double x1, double y1, double x2, double y2) :
Point(x1, y1), m_width(fabs(x2 - x1)), m_height(fabs(y2 - y1)) {
cout << "Constructing Rectangle (" << getX() << ", " << getY() << "), width = " << m_width << ", height = " << m_height << endl;
}
Rectangle::~Rectangle() {
cout << "Destructing Rectangle (" << getX() << ", " << getY() << "), width = " << m_width << ", height = " << m_height << endl;
}
double Rectangle::getWidth() const {
return m_width;
}
double Rectangle::getHeight() const {
return m_height;
}
double Rectangle::getArea() const {
return m_width * m_height;
}
Circle::Circle(double x, double y, double r) : Point(x, y), m_radius(r) {
cout << "Constructing Circle (" << getX() << ", " << getY() << "), radius = " << m_radius << endl;
}
Circle::~Circle() {
cout << "Destructing Circle (" << getX() << ", " << getY() << "), radius = " << m_radius << endl;
}
double Circle::getRadius() const {
return m_radius;
}
double Circle::getArea() const {
return M_PI * m_radius * m_radius;
}
int main() {
Rectangle r(1, 1, 4, 3);
Circle c(2, 2, 2);
cout << "Rectangle area: " << r.getArea() << endl;
cout << "Circle area: " << c.getArea() << endl;
return 0;
}
```
在main函数中,我们创建了一个Rectangle对象和一个Circle对象,并且分别调用它们的getArea()函数计算面积并输出。程序输出如下:
```
Constructing Point (1, 1)
Constructing Rectangle (1, 1), width = 3, height = 2
Constructing Point (2, 2)
Constructing Circle (2, 2), radius = 2
Rectangle area: 6
Circle area: 12.5664
Destructing Circle (2, 2), radius = 2
Destructing Point (2, 2)
Destructing Rectangle (1, 1), width = 3, height = 2
Destructing Point (1, 1)
```
阅读全文