用C++定义一个Point类,派生出Rectangle和Circle类,计算个派生类对象的面积Area()。 要求: ①Point类,Rectangle和Circle类都有成员变量、成员函数; ②分别写出他们的构造函数和析构函数; ③在main函数中实现输出。 ④力争做到数据输入输出的直观性。
时间: 2023-12-03 07:43:35 浏览: 149
c++程序编程
以下是实现代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
protected:
double x, y;
public:
Point(double a, double b): x(a), y(b) {}
virtual ~Point() {}
};
class Rectangle: public Point {
private:
double width, height;
public:
Rectangle(double a, double b, double w, double h): Point(a, b), width(w), height(h) {}
~Rectangle() {}
double Area() {
return width * height;
}
};
class Circle: public Point {
private:
double radius;
public:
Circle(double a, double b, double r): Point(a, b), radius(r) {}
~Circle() {}
double Area() {
return M_PI * pow(radius, 2);
}
};
int main() {
double x, y, w, h, r;
cout << "请输入矩形左下角的坐标:";
cin >> x >> y;
cout << "请输入矩形的宽和高:";
cin >> w >> h;
Rectangle rect(x, y, w, h);
cout << "矩形的面积为:" << rect.Area() << endl;
cout << "请输入圆心坐标:";
cin >> x >> y;
cout << "请输入圆的半径:";
cin >> r;
Circle cir(x, y, r);
cout << "圆的面积为:" << cir.Area() << endl;
return 0;
}
```
运行截图:
```
请输入矩形左下角的坐标:0 0
请输入矩形的宽和高:3 4
矩形的面积为:12
请输入圆心坐标:0 0
请输入圆的半径:5
圆的面积为:78.5398
```
阅读全文