C++设计并测试一个矩形类,属性为矩形的左下与右上角的坐标,矩形水平放置,操作为计算矩形周长和面积,类对象的数据由友元函数来进行访问
时间: 2023-05-30 14:02:46 浏览: 105
```
#include<iostream>
using namespace std;
class Rectangle {
friend double getPerimeter(Rectangle r);
friend double getArea(Rectangle r);
private:
double x1, y1, x2, y2;
public:
Rectangle(double x1, double y1, double x2, double y2) {
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
}
};
double getPerimeter(Rectangle r) {
double length = r.y2 - r.y1;
double width = r.x2 - r.x1;
return 2 * (length + width);
}
double getArea(Rectangle r) {
double length = r.y2 - r.y1;
double width = r.x2 - r.x1;
return length * width;
}
int main() {
Rectangle r(0, 0, 4, 3);
cout << "Perimeter: " << getPerimeter(r) << endl;
cout << "Area: " << getArea(r) << endl;
return 0;
}
```
阅读全文