4. 类的组合。定义一个点Point类,有点坐标属性(x, y),再定义一个矩形Rectangle类,其属性为两个Point点(分别表示矩形对角线上两点的坐标),及含有计算矩形的周长及面积的成员函数;再编写两个Point类的友元函数,分别计算两个点组成的矩形的周长与面积。在主函数中进行测试。使用cpp语言
时间: 2024-03-26 11:39:33 浏览: 109
下面是代码实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point{
private:
double x, y;
public:
Point(double a = 0, double b = 0){x = a; y = b;}
double getx(){return x;}
double gety(){return y;}
friend double distance(Point &a, Point &b);
friend double area(Point &a, Point &b, Point &c);
};
class Rectangle{
private:
Point p1, p2;
public:
Rectangle(Point a, Point b){p1 = a; p2 = b;}
double getLength(){return fabs(p1.getx() - p2.getx());}
double getWidth(){return fabs(p1.gety() - p2.gety());}
double getPerimeter(){return 2 * (getLength() + getWidth());}
double getArea(){return getLength() * getWidth();}
};
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 s = (distance(a, b) + distance(b, c) + distance(c, a)) / 2;
return sqrt(s * (s - distance(a, b)) * (s - distance(b, c)) * (s - distance(c, a)));
}
int main(){
Point p1(0, 0), p2(3, 4), p3(6, 8);
Rectangle r(p1, p2);
cout << "Length: " << r.getLength() << endl;
cout << "Width: " << r.getWidth() << endl;
cout << "Perimeter: " << r.getPerimeter() << endl;
cout << "Area: " << r.getArea() << endl;
cout << "Area of rectangle by two points: " << area(p1, p2, p3) << endl;
cout << "Perimeter of rectangle by two points: " << distance(p1, p2) * 2 + distance(p2, p3) * 2 << endl;
return 0;
}
```
输出结果如下:
```
Length: 3
Width: 4
Perimeter: 14
Area: 12
Area of rectangle by two points: 24
Perimeter of rectangle by two points: 14
```
阅读全文