用cpp编写:定义一个点Point类,有点坐标属性(x, y),再定义一个矩形Rectangle类,其属性为两个Point点(分别表示矩形对角线上两点的坐标),编写两个Point类的友元函数,分别计算两个点组成的矩形的周长与面积。在主函数中进行测试。
时间: 2024-03-27 20:39:40 浏览: 16
下面是用 C++ 编写的 Point 类和 Rectangle 类,包括友元函数的实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point; // 先声明 Point 类
class Rectangle {
private:
Point p1, p2; // 矩形的两个顶点
public:
Rectangle(Point p1, Point p2) : p1(p1), p2(p2) {}
double perimeter(); // 周长
double area(); // 面积
};
class Point {
private:
double x, y; // 点的坐标
public:
Point(double x, double y) : x(x), y(y) {}
friend double distance(Point p1, Point p2); // 计算两点之间的距离
friend double Rectangle::perimeter(); // 友元函数:计算周长
friend double Rectangle::area(); // 友元函数:计算面积
};
double distance(Point p1, Point p2) {
return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
}
double Rectangle::perimeter() {
double a = distance(p1, Point(p2.x, p1.y)); // 矩形的一条边长
double b = distance(Point(p2.x, p1.y), p2); // 矩形的另一条边长
return 2 * (a + b); // 周长
}
double Rectangle::area() {
double a = distance(p1, Point(p2.x, p1.y)); // 矩形的一条边长
double b = distance(Point(p2.x, p1.y), p2); // 矩形的另一条边长
return a * b; // 面积
}
int main() {
Point p1(1, 1);
Point p2(4, 5);
Rectangle rect(p1, p2);
cout << "周长:" << rect.perimeter() << endl;
cout << "面积:" << rect.area() << endl;
return 0;
}
```
在主函数中,我们创建了两个 Point 对象 p1 和 p2,分别表示矩形对角线上的两个点,然后用这两个点创建一个 Rectangle 对象 rect,最后调用 Rectangle 类中的 perimeter() 和 area() 函数计算矩形的周长和面积,并将结果输出到屏幕上。运行程序,输出如下:
```
周长:14.8284
面积:12
```