用cpp编写:定义一个点Point类,有点坐标属性(x, y),再定义一个矩形Rectangle类,其属性为两个Point点(分别表示矩形对角线上两点的坐标),编写两个Point类的友元函数,分别计算两个点组成的矩形的周长与面积。在主函数中进行测试。
时间: 2024-03-27 18:39:00 浏览: 15
```cpp
#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) {}
double getX() const { return x; }
double getY() const { return y; }
friend double distance(Point p1, Point p2); // 声明友元函数
};
class Rectangle {
private:
Point p1, p2;
public:
Rectangle(Point p1, Point p2) : p1(p1), p2(p2) {}
friend double perimeter(Rectangle r); // 声明友元函数
friend double area(Rectangle r); // 声明友元函数
};
double distance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return sqrt(dx * dx + dy * dy);
}
double perimeter(Rectangle r) {
double length = distance(r.p1, r.p2);
double width = distance(Point(r.p1.getX(), r.p2.getY()), Point(r.p2.getX(), r.p1.getY()));
return 2 * (length + width);
}
double area(Rectangle r) {
double length = distance(r.p1, r.p2);
double width = distance(Point(r.p1.getX(), r.p2.getY()), Point(r.p2.getX(), r.p1.getY()));
return length * width;
}
int main() {
Point p1(1, 1);
Point p2(4, 5);
Rectangle r(p1, p2);
cout << "Perimeter: " << perimeter(r) << endl;
cout << "Area: " << area(r) << endl;
return 0;
}
```
这段代码定义了一个Point类和一个Rectangle类。Point类表示一个二维平面上的点,其中包括横纵坐标属性。Rectangle类表示一个矩形,其中包括两个Point点,分别表示矩形对角线上两点的坐标。Rectangle类中声明了两个友元函数perimeter()和area(),用于计算矩形的周长和面积。Point类中声明了一个友元函数distance(),用于计算两个点之间的距离。在主函数中创建了两个Point点和一个Rectangle对象,并调用perimeter()和area()方法分别计算矩形的周长和面积,并输出结果。注意,在Point类中声明友元函数时需要使用friend关键字,在类外定义函数时不需要使用类作用域解析符。