请编程实现一个简易的屏幕窗口模拟,具体要求如下: * 编写 CPoint 类,描述二维平面内的一个坐标点,包含 x,y 两个坐标,重载 >> 运算符以实现输出形如 (x,y) 的信息。 * 编写 CWindow 类,描述平面上的一个窗口,包含如下信息: int id ,窗口唯一标识,为了保证唯一性,可以使用 (int)time(NULL) 返回的时间戳赋值。 char title[255] ,窗口标题 CPoint topleft,bottomright ,左上角和右下角的坐标 两种形态的构造函数: 提供标题和两点坐标的:CWindow(const char* title,CPoint topleft,CPoint bottomright) 提供标题和左上角坐标以及窗口高宽的:CWindow(const char* title,CPoint topleft,int width,int height) 一个静态成员 CWindow* topmost ,指向当前活动窗口,可以初始化为 nullptr 一个 Activate() 方法,将当前窗口置为活动窗口 重载 >> 运算符输出窗口信息,形如 title (x,y)-(x,y) ,参见测试用例输出结果 * 其它成员如果需要请自行编写,例如 CPoint 可以设计 getX 和 getY 接口便于 CWindow 根据高宽计算右下角坐标 主程序生成了三个窗口并随机激活了一个,然后输出了激活后窗口的信息,请参考测试用例的输出进行编程。 */
时间: 2024-02-09 20:09:03 浏览: 26
以下是实现了上述要求的代码:
```cpp
#include <iostream>
#include <cstdio>
#include <ctime>
using namespace std;
class CPoint {
public:
int x, y;
CPoint() {}
CPoint(int x, int y) : x(x), y(y) {}
friend istream& operator>>(istream& is, CPoint& p) {
is >> p.x >> p.y;
return is;
}
};
class CWindow {
public:
int id;
char title[255];
CPoint topleft, bottomright;
static CWindow* topmost;
CWindow() {}
CWindow(const char* title, CPoint topleft, CPoint bottomright) : id((int)time(NULL)), topleft(topleft), bottomright(bottomright) {
strncpy(this->title, title, 254);
this->title[254] = '\0';
}
CWindow(const char* title, CPoint topleft, int width, int height) : id((int)time(NULL)), topleft(topleft) {
this->bottomright.x = topleft.x + width;
this->bottomright.y = topleft.y + height;
strncpy(this->title, title, 254);
this->title[254] = '\0';
}
bool isInside(CPoint point) {
if (point.x >= topleft.x && point.x <= bottomright.x && point.y >= topleft.y && point.y <= bottomright.y) {
return true;
}
else {
return false;
}
}
void Activate() {
topmost = this;
}
friend istream& operator>>(istream& is, CWindow& w) {
is >> w.title >> w.topleft >> w.bottomright;
return is;
}
friend ostream& operator<<(ostream& os, CWindow& w) {
os << w.title << " (" << w.topleft.x << "," << w.topleft.y << ")-(" << w.bottomright.x << "," << w.bottomright.y << ")";
return os;
}
};
CWindow* CWindow::topmost = nullptr;
int main() {
int n = 3;
CWindow windows[n];
for (int i = 0; i < n; i++) {
// 随机生成窗口的位置和大小
int x = rand() % 100;
int y = rand() % 100;
int width = rand() % 20 + 10;
int height = rand() % 20 + 10;
CPoint topleft(x, y);
CWindow window("Window", topleft, width, height);
windows[i] = window;
}
// 随机激活一个窗口
int index = rand() % n;
windows[index].Activate();
// 输出激活后的窗口信息
cout << *CWindow::topmost << endl;
return 0;
}
```
程序中先定义了 `CPoint` 和 `CWindow` 两个类,分别表示一个点和一个窗口。`CWindow` 类中包含了窗口的唯一标识、标题、左上角和右下角的坐标等信息。
其中,静态成员 `CWindow* topmost` 指向当前活动窗口,可以通过 `Activate()` 方法将当前窗口置为活动窗口。
在主程序中,先生成了三个随机位置和大小的窗口,并随机激活了其中一个窗口,最后输出激活窗口的信息。