c++请封装一个矩形类,属性:长 + 宽 ,行为:求面积。 需求:如果有两个矩形,求一个较大矩形并输出其面积。
时间: 2024-03-23 11:36:02 浏览: 66
好的,这里是一个封装矩形类并实现求面积和比较面积的代码,可以满足你的需求:
```cpp
class Rectangle {
private:
double length;
double width;
public:
Rectangle(double l, double w): length(l), width(w) {}
double getArea() const { return length * width; }
bool operator>(const Rectangle& other) const { return getArea() > other.getArea(); }
};
```
我们定义了一个 `Rectangle` 类,它有两个私有属性 `length` 和 `width`,并在构造函数中初始化这两个属性。我们还定义了一个公有方法 `getArea()` 来计算矩形的面积,并且重载了 `>` 运算符来比较两个矩形的面积大小。
接下来,我们可以创建两个矩形对象,比较它们的面积并输出较大矩形的面积:
```cpp
Rectangle rect1(3, 4);
Rectangle rect2(4, 5);
Rectangle maxRect = rect1 > rect2 ? rect1 : rect2; // 比较两个矩形的面积
double maxArea = maxRect.getArea(); // 获取较大矩形的面积
std::cout << "The area of the larger rectangle is " << maxArea << std::endl; // 输出较大矩形的面积
```
输出结果应该为:
```
The area of the larger rectangle is 20
```
希望这个代码可以帮助你!
阅读全文
相关推荐
















