利用我上述的代码实现要求:设计一个矩形类,数据成员为left、top、right、bottom,用来指定矩形的4个顶点坐标,由5个成员函数来赋值(见类定义部分),另有显示函数和加减运算函数。重点提示:(1)加减复合赋值运算,语义定义为:新的矩形的长宽为原两矩形长宽的和或者差,新矩形的左上角坐标同参与加减运算的第一个矩形的左上角坐标;此加减复合赋值运算函数定义为类的成员函数;(2)两个矩形的加减运算,语义定义同上,但不定义为成员函数而是定义为友元函数建立工程(工程名自定),录入上述完整程序,验证结果是否符合设计要求。
时间: 2024-04-21 19:30:14 浏览: 65
好的,以下是一个基于你提供的代码实现矩形类的示例代码:
矩形类的定义 (rect.h):
```cpp
class Rectangle {
int left, top, right, bottom;
public:
Rectangle(int l=0, int t=0, int r=0, int b=0);
Rectangle(const Rectangle& other);
void assign(int l, int t, int r, int b);
void set_left(int l) { left = l; }
void set_right(int r) { right = r; }
void set_top(int t) { top = t; }
void set_bottom(int b) { bottom = b; }
void show() const;
void operator+=(const Rectangle& other);
void operator-=(const Rectangle& other);
friend Rectangle operator+(const Rectangle& lhs, const Rectangle& rhs);
friend Rectangle operator-(const Rectangle& lhs, const Rectangle& rhs);
};
```
矩形类的实现 (rect.cpp):
```cpp
#include <iostream>
#include "rect.h"
Rectangle::Rectangle(int l, int t, int r, int b)
: left(l), top(t), right(r), bottom(b)
{}
Rectangle::Rectangle(const Rectangle& other)
: left(other.left), top(other.top), right(other.right), bottom(other.bottom)
{}
void Rectangle::assign(int l, int t, int r, int b)
{
left = l;
top = t;
right = r;
bottom = b;
}
void Rectangle::show() const
{
std::cout << "left-top point is (" << left << "," << top << ")" << '\n';
std::cout << "right-bottom point is (" << right << "," << bottom << ")" << std::endl;
}
void Rectangle::operator+=(const Rectangle& other)
{
int x = other.right - other.left;
int y = other.bottom - other.top;
right += x;
bottom += y;
}
void Rectangle::operator-=(const Rectangle& other)
{
int x = other.right - other.left;
int y = other.bottom - other.top;
right -= x;
bottom -= y;
}
Rectangle operator+(const Rectangle& lhs, const Rectangle& rhs)
{
int l = lhs.left;
int t = lhs.top;
int r = lhs.right + rhs.right - rhs.left;
int b = lhs.bottom + rhs.bottom - rhs.top;
return Rectangle(l, t, r, b);
}
Rectangle operator-(const Rectangle& lhs, const Rectangle& rhs)
{
int l = lhs.left;
int t = lhs.top;
int r = lhs.right - rhs.right + rhs.left;
int b = lhs.bottom - rhs.bottom + rhs.top;
return Rectangle(l, t, r, b);
}
```
主函数 (main.cpp):
```cpp
#include <iostream>
#include "rect.h"
int main() {
Rectangle rect;
std::cout << "初始rect:" << std::endl;
rect.show();
rect.assign(100, 200, 300, 400);
std::cout << "赋值后rect:" << std::endl;
rect.show();
Rectangle rect1(0, 0, 200, 200);
std::cout << "初始rect1:" << std::endl;
rect1.show();
rect += rect1;
std::cout << "与rect1相加后的rect:" << std::endl;
rect.show();
rect -= rect1;
std::cout << "减去rect1后的rect:" << std::endl;
rect.show();
Rectangle rect2;
rect2 = rect + rect1;
std::cout << "rect与rect1相加所得rect2:" << std::endl;
rect2.show();
rect2 = rect - rect1;
std::cout << "rect减去rect1所得rect2:" << std::endl;
rect2.show();
return 0;
}
```
这段代码实现了一个简单的矩形类,包含了左上角和右下角的坐标,以及赋值、显示、加减运算操作。其中加减运算操作分别使用了成员函数和友元函数实现。你可以将这些代码保存到一个工程中,然后编译运行,验证是否符合你的要求。
阅读全文