定义一个点Point类,有点坐标属性(x, y),再定义一个矩形Rectangle类,其属性为两个Point点(分别表示矩形对角线上两点的坐标),及含有计算矩形的周长及面积的成员函数;再编写两个Point类的友元函数,分别计算两个点组成的矩形的周长与面积。在主函数中进行测试。c++
时间: 2024-03-26 11:39:36 浏览: 53
以下是代码实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x, y;
public:
Point(double _x = 0, double _y = 0) {
x = _x;
y = _y;
}
friend double distance(const Point& p1, const Point& p2) {
return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
}
friend double area(const Point& p1, const Point& p2) {
return distance(p1, p2) * distance(p1, p2);
}
friend double perimeter(const Point& p1, const Point& p2) {
return 2 * (distance(p1, p2) + distance(Point(p1.x, p2.y), Point(p2.x, p1.y)));
}
friend class Rectangle;
};
class Rectangle {
private:
Point p1, p2;
public:
Rectangle(Point _p1 = Point(), Point _p2 = Point()) {
p1 = _p1;
p2 = _p2;
}
double area() const {
return Point::area(p1, p2);
}
double perimeter() const {
return Point::perimeter(p1, p2);
}
};
int main() {
Point p1(0, 0), p2(4, 3);
Rectangle rec(p1, p2);
cout << "Rectangle area: " << rec.area() << endl;
cout << "Rectangle perimeter: " << rec.perimeter() << endl;
return 0;
}
```
运行结果:
```
Rectangle area: 12.25
Rectangle perimeter: 14
```
阅读全文