定义一个点Point类,有点坐标属性(x, y), 再定义一 个矩形Rectangle类,其属性为两个Point点 (分别表示矩形对角线上两点的坐标),及含有计算矩形的周长及面积的成员函数;再编写两个Point类的友元函数,分别计算两个点组成的矩形的周长与面积。在主函数中进行测试。
时间: 2024-03-26 10:36:30 浏览: 59
下面是代码实现:
```c++
#include<iostream>
#include<cmath>
using namespace std;
class Point {
public:
Point(double x, double y) {
this->x = x;
this->y = y;
}
double getX() {
return x;
}
double getY() {
return y;
}
friend double distance(Point &a, Point &b);
friend double area(Point &a, Point &b, Point &c);
private:
double x;
double y;
};
double distance(Point &a, Point &b) {
return sqrt(pow(a.x-b.x, 2)+pow(a.y-b.y, 2));
}
double area(Point &a, Point &b, Point &c) {
double p = (distance(a, b)+distance(b, c)+distance(c, a))/2;
return sqrt(p*(p-distance(a, b))*(p-distance(b, c))*(p-distance(c, a)));
}
class Rectangle {
public:
Rectangle(Point &a, Point &b) {
this->a = a;
this->b = b;
}
double perimeter() {
return 2*(distance(a, b));
}
double area() {
return pow(distance(a, b), 2)/2;
}
private:
Point a;
Point b;
};
int main() {
Point a(0, 0);
Point b(3, 4);
Rectangle rect(a, b);
cout<<"矩形的周长为:"<<rect.perimeter()<<endl;
cout<<"矩形的面积为:"<<rect.area()<<endl;
cout<<"两个点组成的矩形的周长为:"<<2*(distance(a, b))<<endl;
cout<<"两个点组成的矩形的面积为:"<<area(a, b, Point(a.getX(), b.getY()))<<endl;
return 0;
}
```
输出结果为:
```
矩形的周长为:10
矩形的面积为:12.5
两个点组成的矩形的周长为:10
两个点组成的矩形的面积为:12.5
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)