定义一个Point类,派生出Rectangle类和Circle类,计算各派生类对象的面积Area()C++
时间: 2023-11-27 15:50:19 浏览: 163
下面是一个简单的实现:
```c++
#include <iostream>
using namespace std;
class Point {
protected:
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
};
class Rectangle : public Point {
private:
int width, height;
public:
Rectangle(int x = 0, int y = 0, int width = 0, int height = 0) : Point(x, y), width(width), height(height) {}
int Area() { return width * height; }
};
class Circle : public Point {
private:
int radius;
public:
Circle(int x = 0, int y = 0, int radius = 0) : Point(x, y), radius(radius) {}
double Area() { return 3.14 * radius * radius; }
};
int main() {
Rectangle rect(1, 2, 3, 4);
Circle circle(5, 6, 7);
cout << "Rectangle area: " << rect.Area() << endl;
cout << "Circle area: " << circle.Area() << endl;
return 0;
}
```
Point 类作为基类,Rectangle 和 Circle 类分别继承 Point 类。Rectangle 和 Circle 类都有一个 Area 函数,分别计算矩形和圆的面积。在 main 函数中创建一个 Rectangle 对象和一个 Circle 对象,并分别调用它们的 Area 函数输出结果。
阅读全文