1.定义一个Point类,派生出Rectangle类和Circle类,计算各派生类对象的面积Area() (不能使用构造函数进行初始化)
时间: 2023-12-03 15:44:02 浏览: 106
以下是定义Point类,派生出Rectangle类和Circle类,计算各派生类对象的面积Area()的示例代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point {
protected:
double x, y;
public:
Point(double x = 0, double y = 0) : x(x), y(y) {}
double getX() const { return x; }
double getY() const { return y; }
};
class Rectangle : public Point {
private:
double width, height;
public:
Rectangle(double x = 0, double y = 0, double width = 0, double height = 0) : Point(x, y), width(width), height(height) {}
double getWidth() const { return width; }
double getHeight() const { return height; }
double Area() const { return width * height; }
};
class Circle : public Point {
private:
double radius;
public:
Circle(double x = 0, double y = 0, double radius = 0) : Point(x, y), radius(radius) {}
double getRadius() const { return radius; }
double Area() const { return M_PI * pow(radius, 2); }
};
int main() {
Rectangle rect(0, 0, 5, 10);
Circle circle(0, 0, 5);
cout << "Rectangle area: " << rect.Area() << endl;
cout << "Circle area: " << circle.Area() << endl;
return 0;
}
```
在这个示例中,定义了一个基类Point,它代表一个二维坐标点。Rectangle和Circle都是从Point派生出来的类。Rectangle和Circle都有各自的Area()函数来计算它们的面积。Area()函数在Rectangle类中计算矩形面积,在Circle类中计算圆面积。在main()函数中创建了一个Rectangle对象和一个Circle对象,并分别调用它们的Area()函数来计算它们的面积。
阅读全文